此上传脚本是否正确


Is this uploading script correct?

我有一个名为"Mobile_App"的文件夹,该文件夹中有一个html页面,其中包含一个文件输入,一个上传文件的php脚本,以及一个名为"ImageFiles"的文件夹。

问题是文件没有上传到"图像文件"中。我想知道的是,在将文件上传到"Imagefiles"文件夹时,下面的代码是否正确,或者不正确,我怎样才能让它正常工作?

下面是上传文件的 php 脚本(文件输入称为"fileImage"):

<?php
   $destination_path = $_SERVER['DOCUMENT_ROOT']."/ImageFiles";
   $result = 0;
   $target_path = $destination_path . basename( $_FILES['fileImage']['name']);
   if(move_uploaded_file($_FILES['fileImage']['tmp_name'], $target_path)) {
      $result = 1;
   }
   sleep(1);
?>

首先,文件夹名称和文件名之间没有/。 其次,您不需要具有文档根目录。 更正的代码:

<?php
   $destination_path = "/ImageFiles";
   $result = 0;
   $target_path = $destination_path . "/" . basename( $_FILES['fileImage']['name']);
   if(move_uploaded_file($_FILES['fileImage']['tmp_name'], $target_path)) {
      $result = 1;
   }
   sleep(1);
?>

No.您根本没有检查上传是成功还是失败。您也不会检查文件名冲突,您的脚本会很乐意用新文件覆盖任何现有文件。

<?php
if ($_FILES['fileImage']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['fileImage']['error']);
}
...
$target_path = etc...
...
if (file_exists($target_path)) {
   die("$target_path exists already");
}
// got here, must be ok to proceed
if (move_uploaded_file(....)) {
etc...

此处定义了上传错误代码。