Home > AI > Uncategorized

php – 提示undefined index的几种解决方法

平时用$_post[''],$_get['']获取表单中参数时会出现Notice: Undefined index: --------
我们经常接收表单POST过来的数据时报Undefined index错误,如下:
     $act=$_POST['action']; 
用以上代码总是提示 
Notice: Undefined index: action in D:\test\post.php on line 20 
另外,有时还会出现 
Notice: Undefined variable: Submit ...... 等一些这样的提示 

出现上面这些是 PHP 的提示而非报错,PHP 本身不需要事先声明变量即可直接使用,但是对未声明变量会有提示。一般作为正式的网站会把提示关掉的,甚至连错误信息也被关掉。

解决方法:

方法1:服务器配置修改
修改 php.ini 中的 error配置下错误显示方式:将error_reporting = E_ALL 修改为

error_reporting = E_ALL & ~E_NOTICE 

修改后重启下APCHE服务器,方可生效。

方法2:对变量进行初始化。

方法3:做判断

isset($_post['']),empty($_post['']) if --else 

方法4:在出现notice代码之前加上@,@表示这行有错误或是警告不要输出,@username=_post[‘username’];
在变量前面 加上一个 @ ,如

 if (@$_GET['action']=='save') { ... 

方法5:最后一种很实用 ,通过这个函数进行传递值。

function _get($str){ 
$val = isset($_GET[$str]) ? $_GET[$str] : null; 
return $val; 
} 
Related posts:

Leave a Reply