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
.
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'])));