未定义的索引通知

时间:2015-01-25 00:15:00

标签: php html undefined isset notice

我已经尝试解决这个问题多年了,但是当我尝试上传文件时,我收到了“undefined index”通知。任何帮助都会很棒!我在第38行得到错误,如果这有帮助的话,我认为这也可能与我的表格有关。

HTML表单:

    <form action="UploadFileCodeImage.php" method="post"enctype="multipart/form-data">
    Upload image (JPG, JPEG, PNG, or GIF):<br/>
    <input type="file" name="file" id="file"><br/>
    <input type="submit" value="submit" name="file">
    </form>

PHP:

<?php
$destination = "C:\xampp\htdocs\Uploaded files\CS\Image";
$target_file = $destination . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$filetype = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = filesize($_FILES["file"]["Temp"]);
    if($check !== false) {
        echo "Voila! - " . $check["file"];
        $uploadOk = 1;
    } else {
        echo "Error!";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 50000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($filetype != "jpg" && $filetype != "png" && $filetype != "jpeg"
&& $filetype != "gif") {
    echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["Temp"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
    } else {
        echo "Error!";
    }
}
?> 

2 个答案:

答案 0 :(得分:1)

让我概述一下代码中的错误。

您有两个带有相同名称的表单元素“file”;这是一场冲突。

<input type="file" name="file" id="file">
                   ^^^^^^^^^^^

<input type="submit" value="submit" name="file">
                                    ^^^^^^^^^^^

然后您的条件语句if(isset($_POST["submit"]))基于名为“submit”的提交按钮;它不存在,所以没有任何东西会被执行。

因此,请将提交按钮重命名为“提交”。

然后您的["Temp"]无效,根据手册,所有内容都应为["tmp_name"]

出现在

$check = filesize($_FILES["file"]["Temp"]);

if (move_uploaded_file($_FILES["file"]["Temp"], $target_file)) {

然后是这一行:

$destination = "C:\xampp\htdocs\Uploaded files\CS\Image";

应该有两个斜杠(编辑)

$destination = "C:\xampp\htdocs\Uploaded files\CS\Image\\";

因为$destination . basename($_FILES["file"]["name"]folderImage.jpg翻译为folder/Image.jpg,否则会导致错误。


  • 还要确保目标文件夹具有适当的写入权限。

答案 1 :(得分:-1)

“Temp”不是有效密钥。而是使用tmp_name

if (move_uploaded_file($_FILES["file"]["Temp"], $target_file)) {

应该是

if (isset($_FILES["file"]["tmp_name"]) && move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {