drus39136
2019-05-11 03:18
浏览 108

为什么我在使用move_uploaded_file函数后有一个损坏的图像文件

I have a form:

<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>

I have php code:

$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';

This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.

I had to change the system of uploading the image by doing this:

 $file_content = file_get_contents($file['tmp_name']);
 $file_dump = file_put_contents($location, $file_content);

This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpthuyh1678 2019-05-11 04:14

    In your code by using

    $ext = explode(",", $file['type'])[0];
    

    you get the extension as image/your_image_type. Then you are appending that with the file name, which will create an invalid image. To get the extension, you can do as follows

    $ext= explode("/", $file['type'])[1];
    

    or

    $ext = strtolower(end(explode('.',$_FILES['image']['name'])));
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题