php中Notice: Undefined index: upfile怎么解决?

总出现这个,以下是代码,怎么解决?
<?php
require("conn.php");

//upload the files
$upfile = $_FILES['upfile'];
$name = $upfile['name'];
$type = $upfile['type'];
$size = $upfile['size'];
$tmp_name = $upfile['tmp_name'];

switch($type){
case 'image/pjpeg':$ok=1;break;
case 'image/jpeg':$ok=1;break;
case 'image/png':$ok=1;break;
case 'image/gif':$ok=1;break;
}

if($ok==1){
move_uploaded_file($tmp_name,'uploads/$token_name');
}
// print_r($file);

//add the content
if(!empty($_POST['title'])){
$title = $_POST['title'];
}

if(!empty($_POST['content'])){
$content = $_POST['content'];
}

if(!empty($_POST['file'])){
$file = $_POST['file'];
}

function addContent($title,$content,$file){
$sql = "insert into `content` values('',$title,$content,$file)";
$result = mysql_query($sql);
if($result){
echo "成功添加文章!";
}else{
echo "添加文章失败!";
}
}

addContent($title,$content,$file);

?>
<html>
<form action="content.php" method="post" enctype="multipart/form-data" name="file">
<!--标题:<input type="text" name="title"><br/>
内容:<textarea name="content"></textarea><br/>-->
图片:<input type="file" name="upfile"><br/>
<input type="submit" value="提交">
</form>
<a href="list.php">查看</a>
</html>

第1个回答  推荐于2018-05-18
这个一般没什么问题,不会影响程序的运行。但是是一个很不好的习惯。

当你调用了未定义的变量时就是产生Notice级别的错误,你可以通过修改php.ini中的错误信息报告级别来屏蔽该信息。如,将
error_reporting = E_ALL
修改为
error_reporting = E_ALL & ~E_NOTICE

举例来说
$upfile = $_FILES['upfile']; 如果$_FILES['upfile']不存在就报错了,例如你并没有上传任何文件的时候,正确的是
if (isset($_FILES['upfile'])) {
//检查$_FILES['upfile']是否存在,只有它存在的时候才进行对上传的文件的处理

...处理上传的文件...

}

同样的,在你后面的处理中
if(!empty($_POST['title'])){
$title = $_POST['title'];
}
这个写法就是好的,然而
addContent($title,$content,$file); 就又有问题了。上面你写了,如果title不为空,那么$title = $_POST['title'];那么title为空呢,$title就又变成未定义了。

建议楼主养成良好编码习惯,这样同时也能避免一些问题的产生。如,你的代码可能会在数据库中插入一条空记录。本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网