-1

可能重复:
无法在 PHP 中上传文件

我正在尝试学习用 PHP 编写文件上传脚本。我不知道为什么这不起作用。请看一看


<?php
$name=$_FILES["file"]["name"];

if(isset($name)) {
    if(!empty($name)) {
        echo $name;
    }
    else {
        echo 'Please choose a file';
    }
}
?>

它给出了一条错误消息Notice: Undefined index: file in


html部分是


<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" /> 
<input type="submit" name="submit" value="Submit" /></form>

我在 Windows 上使用 wamp。错误的原因可能是什么?

4

3 回答 3

2

您需要在执行 PHP 代码之前检查表单是否已提交:

<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {

    if (isset($_FILES["file"]["name"])) {
        $name = $_FILES["file"]["name"];

        if(!empty($name)) {
            echo $name;
        }
        else {
            echo 'Please choose a file';
        }
    }
}
?>
于 2012-10-01T16:23:55.153 回答
1

线索在错误消息中。FILES 数组中不存在索引“文件”。猜测是因为您在提交表单之前有此代码?

于 2012-10-01T16:33:08.557 回答
0

首先检查它是否存在,

if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded

然后检查您对字段组件的使用。

$_FILES['userfile']['name']  # The original name of the file on the client machine. 
$_FILES['userfile']['type']  # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted. 
$_FILES['userfile']['size']  # The size, in bytes, of the uploaded file. 
$_FILES['userfile']['tmp_name']  # The temporary filename of the file in which the uploaded file was stored on the server. 
$_FILES['userfile']['error']  # The error code associated with this file upload
于 2012-10-01T16:25:54.730 回答