Upload Images Through PHP Using Unique File Names

upload images through php using unique file names

You may want to consider the PHP's uniqid() function.
This way the code you suggested would look like the following:

$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
// do some checks to make sure the file you have is an image and if you can trust it
move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name);

Also keep in mind that your server's random functions are not really random. Try random.org if you need something indeed random. Random random random.

UPD: In order to use random.org from within your code, you'll have to do some API requests to their servers. The documentation on that is available here: www.random.org/clients/http/.

The example of the call would be: random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new. Note that you can change the min, max and the other parameters, as described in the documentation.

In PHP you can do a GET request to a remote server using the file_get_contents() function, the cURL library, or even sockets. If you're using a shared hosting, the outgoing connections should be available and enabled for your account.

$random_int = file_get_contents('http://www.random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new');
var_dump($random_int);

Upload image with unique name

A simple way to get a unique filename is to get the current Unix time in milliseconds and append (or prepend) that to the filename. The command to use is microtime().

For example:

$target_file = $target_dir . microtime() . basename($_FILES["fileToUpload"]["name"]);

You could also try things like hashing the file to get a unique hash with low probability of collisions, but this is faster and just as effective.

php Unique filename when uploading

You can use the uniqid() function to generate a unique ID

/**
* Generate a unique ID
* @link http://www.php.net/manual/en/function.uniqid.php
* @param prefix string[optional] <p>
* Can be useful, for instance, if you generate identifiers
* simultaneously on several hosts that might happen to generate the
* identifier at the same microsecond.
* </p>
* <p>
* With an empty prefix, the returned string will
* be 13 characters long. If more_entropy is
* true, it will be 23 characters.
* </p>
* @param more_entropy bool[optional] <p>
* If set to true, uniqid will add additional
* entropy (using the combined linear congruential generator) at the end
* of the return value, which should make the results more unique.
* </p>
* @return string the unique identifier, as a string.
*/
function uniqid ($prefix = null, $more_entropy = null) {}

Giving uploaded images a unique name for mysqli

My solution is to generate a random string for each uploaded file, i.e.:

<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}

function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}

?>

How to give the uploaded image file a unique filename

You can use PHP's random functions to create random strings for the uploaded file.

mt_rand()

md5()

substr()

So, please modify the line:

$target = "images/".basename($image);

To

$target = "images/". substr(md5(mt_rand(0, 9999)), 0, 21) . '-' . basename($image);

Explanation:

  1. You are adding random string to uploaded file using PHP functions.

  2. Using random strings to rename/save uploaded files fix a severe issue: An image my get overridden if the same image name's file is uploaded.

  3. The uploaded file now has 21 random characters prepended to it. So, there is hardly possibility to have file with same name.

Unique file name when uploading using uniqid()

You should really get into the habit of using error checking. As your code sits right now I can upload ANYTHING and your code will save it as a jpg image.

Start by checking to see if the user even selected a file for upload.

Then compare the file type to a predetermined list of allowed file types.

Then save it as the file type that was uploaded. Which may not always be a jpg. As your code sits right now, if I upload a gif or png file... it will save it as a jpg. Thereby rendering the image useless because it is not a jpg.

Your upload process with error checking...

<?php
$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if(isset($_POST["upload"]) && $_POST["upload"] == 'changer') {

// set some basic variables
$fileName = $_FILES["image"]["name"]; // The file name
$fileTempLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$type = strtolower(substr(strrchr($fileName,"."),1));
if($type == 'jpeg' || $type == 'jpe') { $type = 'jprg'; } // make a jpeg or jpe file a jpg file

if (!$fileTempLoc) { // if no file selected
die ('<div align="center" style="color:#ff0000;"><br /><h3>ERROR: Please select an image before clicking the upload button.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');
} else {

// This is the allowed list (images only)
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/jpe',
'image/gif',
'image/png'
);

// check to see if the file being uploaded is in our allowed list
if(!in_array($_FILES['image']['type'], $acceptable) && !empty($_FILES["image"]["type"])) { // Is file type in the allowed list
die ('<div align="center" style="color:#ff0000;"><br /><h3>Invalid file type. Only JPEG, JPG, JPE, GIF and PNG types are allowed.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');

} else {

if ($_FILES["image"]["error"] > 0) {

//Bad Output for form results red text
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

} else {
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.'.$type;
move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
$file="images/".$new_image_name;
$image_title = addslashes($_REQUEST['image_title']);
$sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}

//Good Output for form results green text
echo '
<div style="padding:10px;">
<h2 style="font-size: 28px;">Success!</h2>
<p style="font-size: 18px;">Your file has been successfully uploaded!</p>
</div>';
mysql_close();
} // end if no errors
} // end if in allowed list
} // end if no file selected
} // end if form submitted
?>

The form...

<form enctype="multipart/form-data" action="<?php echo $FormAction ?>" method="post" name="changer">
<input type="file" name="image" id="image" />
<input name="submit" type="submit" value="Upload">
<input type="hidden" name="upload" id="upload" value="changer" />
</form>

One final note... Do yourself a favor and stop using mysql. Start using pdo_mysql instead. mysql was deprecated in PHP version 5.5 and totally removed in PHP version 7. If you're using mysql code, your code will soon stop functioning completely.

Best method to generate unique filenames when uploading files PHP

I usually either create a UID using uniqid() function for the filename or create a folder with the name of the username who is uploading the file and leave the original filename. The disadvantage of the first one is that you will have to save the original filename somewhere to show to the user.

Create a unique name for the uploaded image

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


Related Topics



Leave a reply



Submit