PHP文件上传脚本无法上传

时间:2012-11-24 01:43:49

标签: php forms file file-upload

在一个页面上有一个小表格,其中包含以下代码,

<div class="postcomment">
<form id="comments" action="insertcomment.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment" id="commentfield">
<input type="submit" name="submit" value="Post comment" class="button">
<br>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Image: <input type="file" name="image" />
<br>
</div>

一旦用户通过浏览表单添加图片,然后转到下面的insertcomment.php代码

$target_path = "images/";

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

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $file_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

由于某种原因,它显示错误而未显示在images目录中,错误是:解析错误:语法错误,/homepages/21/d417005970/htdocs/rk8479/htdocs/insertcomment.php中的意外T_IF第18行

1 个答案:

答案 0 :(得分:1)

试试这个 HTML

<div class="postcomment">
<form id="comments" action="insertcomment.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment" id="commentfield">
<br>
Image: <input type="file" name="image" />
<br>
<input type="submit" name="submit" value="Post comment" class="button">
</form>
</div>

PHP CODE(你试图在同一页面上使用它,你可以检查是否(isset($ _ POST ['submit']))

if($_FILES['image']['size'] > 0){
        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $extension = end(explode(".", $_FILES["image"]["name"]));
        if ((($_FILES["image"]["type"] == "image/gif")
        || ($_FILES["image"]["type"] == "image/jpeg")
        || ($_FILES["new_image"]["type"] == "image/png")
        || ($_FILES["image"]["type"] == "image/pjpeg"))
        && ($_FILES["image"]["size"] < 1048576)
        && in_array($extension, $allowedExts))
          {
          if ($_FILES["image"]["error"] > 0)
            {
            $error_message = $_FILES["image"]["error"];
            }
          else
            {

            if (file_exists("images/" . $_FILES["image"]["name"]))
              {
              $error_message = $_FILES["image"]["name"] . " " . $LANG['image_exist'];
              }
            else
              {
              if(move_uploaded_file($_FILES["image"]["tmp_name"],
              "images/" . $_FILES["image"]["name"])) {  
              // success
              $image_name = $_FILES["image"]["name"];
              } else {
              $error_message = "Upload Failed!";
              }
              }
            }
          }
        else
          {
          $error_message = "Error: May be different ext or size";
          }
    }