【问题标题】:Image upload script not working correctly图片上传脚本无法正常工作
【发布时间】:2016-03-04 07:42:27
【问题描述】:

您好,我需要一些帮助来将图片上传到我的网站,我已经更改了这个脚本几次,但我就是无法让它正常运行?

当我尝试上传任何图像时,脚本似乎失败并且没有更新记录以及没有上传图像?我对脚本做错了吗?

if(isset($_POST['uploadimage'])){
    $user = $_POST['user'];
    $target_dir = "userimg/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

 $check = getimagesize($_FILES["fileToUpload"]);
  if($check !== false) {
        $uploadOk = 1;
  } else {
      $imgerror = 1;
        $uploadOk = 0;
  }

// Check if file already exists
if (file_exists($target_file)) {
    $imgerror = 2;
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"] > 500000) {
    $imgerror = 3;
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    $imgerror = 4;
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $filenameimg = basename( $_FILES["fileToUpload"]);
        mysqli_query($conn, "UPDATE friends_list SET display_img = '$filenameimg' WHERE id = '$user'");
        $imgerror = 6;
    } else {
        $imgerror = 5;
    }
}
}

【问题讨论】:

  • 查看以下链接 php.net/manual/en/mysqli.error.phpphp.net/manual/en/function.error-reporting.php 并将其应用于您的代码。
  • 在代码运行时使用错误报告工具是否是个好主意,以防出现问题,如果我这样做,用户是否能够查看出现的错误?跨度>
  • 只在测试时使用。是的,这些会出现在用户面前。如果你看到他们,他们也会;-)
  • 下次遇到困难时我会记住这一点,非常感谢! :)

标签: php html mysql image uploading


【解决方案1】:

您似乎在这里遗漏了几个重要部分,导致问题的第一部分是您的 basename 函数,您没有包括文件名。

$target_file = $target_dir . basename($_FILES["fileToUpload"]);

应该是

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

而要获取图片大小,也需要使用同样的流程:

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

也可以利用这个想法来更改您的“检查文件大小”部分,我不会为您完成您的工作,但我会向您发送正确的方向。 您还需要记住添加tmp_name 以移动上传的文件。

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

纠正这些错误后,图像应该可以正确处理。除非你得到任何其他错误?

【讨论】:

  • 没关系,不用担心,正如@Fred -ii- 上面指出的那样,如果您不确定错误发生在哪里,您可以使用错误报告功能来提供更好的想法。您还应该考虑在您的代码中运行一些额外的检查,以确保图像不会被上传给错误的用户,以及如果两个用户想要添加两个具有相同名称的不同图像(这种情况可能会发生)该怎么办。目前您只是否认这一点,但这实际上取决于您的脚本使用情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多