Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a unique name for the uploaded image

Tags:

php

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?

like image 291
Nahid Suhail Avatar asked Mar 16 '16 08:03

Nahid Suhail


1 Answers

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 the file type from upload file name.
  • Use php function as below

CODE

// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));
like image 142
BobGao Avatar answered Sep 29 '22 12:09

BobGao