I have a certain code for image upload .I found this on the internet and there was no explanation of the code either.What i can understand from the code is that php upload a certain file makes it a temporary file and then moves the temporary file to the original location
Code Looks something like this
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
What happens now is that when i try to provide an unique name to the image when it is being moved using the move_uploaded_file
then a file does come up inside the folder but it says an invalid file and with the extension type of file
.
My code for trying to achieve the same but with an unique name/id for the uploaded image.
$uniquesavename=time().uniqid(rand());
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $uniquesavename);
How to achieve the same as before and could you please explain me the previous code as well?
Sample code:
// Get file path from post data by using $_FILES
$filename = $_FILES["img"]["tmp_name"];
// Make sure that it's a valid image which can get width and height
list($width, $height) = getimagesize( $filename );
// Call php function move_uploaded_file to move uploaded file
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
Please try this one:
// Make sure this imagePath is end with slash
$imagePath = '/root/path/to/image/folder/';
$uniquesavename=time().uniqid(rand());
$destFile = $imagePath . $uniquesavename . '.jpg';
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $destFile);
Edit 1: To get image type in two ways:
// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With