php代码出错(文件上传)

时间:2011-08-16 20:33:51

标签: php

我收到以下错误:

注意:未定义的索引:第5行的C:\ wamp \ www_upload \ index.php中的图像

注意:未定义的索引:第7行的C:\ wamp \ www_upload \ index.php中的图像

以下是代码:

<?php

$target_path = "images/";

$target_path = $target_path . basename( $_FILES['theimage']['name']);

if(move_uploaded_file($_FILES['theimage']['tmp_name'], $target_path)) {
echo "<p>The image ".  basename( $_FILES['theimage']['name']). " has been uploaded</p>";
} else{
echo "<p>There was an error uploading the image, please try again!</p>";
}  

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
</head>
<body>

<form enctype="multipart/form-data" action="index.php" method="POST">
<fieldset>
<input name="theimage" type="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>



</body>
</html>

有关如何解决此问题的任何想法吗?

3 个答案:

答案 0 :(得分:2)

检查以确保在尝试对其进行任何操作之前,您已在$_FILES$_POST中获取数据:

<?php
    if(isset($_FILES)) {        // if(isset($_POST)) 
                                // would work as well
        $target_path = "images/";
        $target_path = $target_path . basename( $_FILES['theimage']['name']);
        if(move_uploaded_file($_FILES['theimage']['tmp_name'], $target_path)) {
            echo "<p>The image ".  basename( $_FILES['theimage']['name']). 
                " has been uploaded</p>";
        } else {
            echo "<p>There was an error uploading the image!</p>";
        } 
    } 
?>

答案 1 :(得分:2)

<?php
if(!empty($_FILES['theimage'])) {
    // YOUR CURRENT PHP CODE HERE
?>

问题是上传脚本正在执行,即使没有发布任何内容(例如第一次加载页面时)。

答案 2 :(得分:0)

将提交按钮更改为:

<input type = 'submit' name = 'theSubmitBtn' value = 'Upload'>

然后,如果检查:

,请将所有PHP代码包装在此处的顶部
if(isset($_POST['theSubmitBtn'])) {

... Your Code ...

}

看看它是否适合您。另外,如果要在生产环境中使用它,还需要添加更多错误检查。