Reputation: 29
I am trying to make an upload script, so when user upload something it saves into uploads folder. I was getting problem of similar names when uploading images, so I tried method which is given below to rename file to random number but I am getting problem that it is missing dot (.
) in image name.
Old script:
move_uploaded_file($_FILES["image_file"]["tmp_name"],
"uploads/" . $_FILES["image_file"]["name"]);
New Script to rename file to random number:
$newfilename = rand(1,99999) . end(explode(".",$_FILES["image_file"]["name"]));
move_uploaded_file($_FILES["image_file"]["tmp_name"], "uploads/" . $newfilename);
I want the file name like this
41150.jpg
but it saves file like this 41150jpg
Upvotes: 0
Views: 7978
Reputation: 3236
Change the code to:
$newfilename = rand(1,99999) . '.' . end(explode(".", $_FILES["image_file"]["name"]));
Upvotes: 0
Reputation: 5108
You missed the dot:
$newfilename = rand(1,99999) . '.' . end(explode(".",$_FILES["image_file"]["name"]));
Basically you generate a random number, add a dot to separate the extension and then slice the original filename by dots and take the last part (which should be the extension itself). The extension is without the dot and you add it to what you already prepared.
Don't forget that random number will not generate a unique filename.It's possible that you'll overwrite your old files. And the more files you have the more this can happen.
To avoid this you can use a timestamp insteaf of (or together with) random number. This way you'll be sure that every second the filename will be unique:
$newfilename = time() . '_' . rand(100, 999) . '.' . end(explode(".",$_FILES["image_file"]["name"]));
The timestamp and three random numbers separated by underscore should be fine.
Upvotes: 3