图片上传脚本无法正常工作

时间:2015-11-30 15:50:53

标签: php html mysql image uploading

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

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

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;
    }
}
}

1 个答案:

答案 0 :(得分:0)

您好像错过了几个重要的部分,导致问题的第一部分是您的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)) {

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

相关问题