用php上传图片

时间:2014-09-13 19:33:23

标签: php html

我正在尝试使用我的表单数据上传图片,但我收到错误。

在我的表单中,文件的行是:

<li id="li_6" >
    <label class="description" for="file">Filename:</label>
    <div>
        <input type="file" name="file" id="file"><br>
    </div><p class="guidelines" id="guide_5"><small>Select the image to upload.</small></p> 
    </li>

这是上传脚本:

if(isset($_POST['title'])) {

            $allowedExts = array("gif", "jpeg", "jpg", "png");
            $temp = explode(".", $_FILES["file"]["name"]);
            $extension = end($temp);

            if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/pjpeg")
            || ($_FILES["file"]["type"] == "image/x-png")
            || ($_FILES["file"]["type"] == "image/png"))
            && ($_FILES["file"]["size"] < 60000)
            && in_array($extension, $allowedExts)) {
              if ($_FILES["file"]["error"] > 0) {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
              } else {
                echo "Upload: " . $_FILES["file"]["name"] . "<br>";
                echo "Type: " . $_FILES["file"]["type"] . "<br>";
                echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
                echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
                if (file_exists("upload/" . $_FILES["file"]["name"])) {
                  echo $_FILES["file"]["name"] . " already exists. ";
                } else {
                  move_uploaded_file($_FILES["file"]["tmp_name"],
                  "media/uploads/" . $_FILES["file"]["name"]);
                  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
                }
              }
            } else {
              echo "Invalid file";
            }
            $img_url = '/media/uploads/'.$_FILES["file"]["name"];
            $title = $_POST['title'];
            $description = $_POST['description'];
            $type = $_POST['description'];
            $startPrice = $_POST['startPrice'];
            $reservePrice = $_POST['reservePrice'];
            $buyPrice = $_POST['buyPrice'];

不太确定哪里出错了。我看了一遍。我的意思是代码直接来自手册..它应该可以工作!

然而,我收到此错误:

> 
A PHP Error was encountered

Severity: Notice

Message: Undefined index: file

Filename: controllers/user.php

Line Number: 76

1 个答案:

答案 0 :(得分:3)

此错误的最常见原因是忘记设置enctype的{​​{1}}参数:

<form>

更多信息:Why File Upload didn't work without enctype?