Click here to Skip to main content
15,886,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello. I have a problem and so I want to do something when the user adds a new picture, then his name will change to a string of unique numbers. By writing code I wanted to write on the server say (the user uploads a photo.jpg and it writes on the server) and now I would like to do so. (The user uploads the image.jpg, the server is renamed to 102399_2.jpg (something like that) and saves it in the directory and in the database).
 
With this code I used
PHP
$target_dir = "photos/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

PHP
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))


What I have tried:

With change
PHP
$target_file
Posted
Updated 3-Apr-17 5:32am

1 solution

The trouble with "a string of unique numbers" is generating them so they are not repeated - random numbers don't guarantee that (in my experience they seem to positively guarantee that they do repeat...)

There is a solution though: GUIDs.
Have a look at this: PHP: com_create_guid - Manual[^] it generates a string that is very unlikely to repeat at all. I use them for file storage, with a DB entry which converts them back to file name and the user that uploaded it, allowing for multiple users with the same file name but different content.
 
Share this answer
 
Comments
Mike CJ 3-Apr-17 11:42am    
I have question to you. How I can use this code
<?php

function GUID()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}

return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

?>
Mike CJ 3-Apr-17 11:59am    
How I can add format file with use GUID ?
OriginalGriff 3-Apr-17 12:10pm    
You store the file to disk using the GUID as the filename.
You then store the original file name, user, and GUID to you DB so you can retrieve them later.
Mike CJ 3-Apr-17 12:12pm    
Can I do so to change only the name without the file format?
OriginalGriff 3-Apr-17 12:38pm    
File names do not control format: that is controlled by the file content.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900