Upload Script - Add Random Number to File Name

I have the below php code on our intranet…I need the file that gets upload to add some sort of random number to the file name that gets upload to prevent duplicate file names, accidentally overwrites, etc. If I can keep as is, but just add a 5-digit random number to the end of the file name once it is uploaded, I’ll be happy.

Also, I’m having an issue that the file isn’t actually being upload to the specified path (or maybe I have something wrong in the code). It should be saved to the folder “files” within the “cases” directory, but right now it just gets dropped into the “cases” directory (same directly as the html page).

Can anyone help really quick?

[php]<?php
$allowed_filetypes = array(’.jpg’,’.gif’,’.bmp’,’.png’,’.pdf’,’.JPG’,’.GIF’,’.BMP’,’.PNG’,’.PDF’);
$max_filesize = 524288;
$upload_path = ‘./files’;
$filename = $_FILES[‘userfile’][‘name’];
$ext = substr($filename, strpos($filename,’.’), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed. Only jpg, gif, bmp, png or pdf is allowed. Please try again. ');
if(filesize($_FILES[‘userfile’][‘tmp_name’]) > $max_filesize)
die(‘The file you attempted to upload is too large. Please try again or call 1-xxx for help.’);
if(!is_writable($upload_path))
die(‘An error occured during your upload. Path unavailable. Please call 1-xxx for help.’);
if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’],$upload_path . $filename))
echo ‘Your file upload was successful, view the file here’;
else
echo ‘There was an error during the file upload. Please try again or call 1-xxx for help.’;
?>[/php]

Most of the script looks okay. Have you set in the ini file the upload directory as “cases” cause you don’t specify it in the script, that might be the issue there. For the filename number addition, that’s fairly easy, although understand that a if you don’t check that the file already exists even with a random number attached you may still overwrite a file.
[php]if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’],$upload_path . $filename. mt_rand(10000))[/php]

Thanks @fastsol! That worked for the random number…but, for the other part, I don’t have an ini file for it. Should i? How do I get that?

Actually, I get the following code error:
“Warning: mt_rand() expects exactly 2 parameters, 1 given in /home/content/65/10778365/html/cases/upload_file.php on line 13”

I didn’t think you needed to have the 2nd parameter but okay, put in 999999

I suggest looking up parameters for function in the PHP manual.

http://php.net/manual/en/function.mt-rand.php

Sponsor our Newsletter | Privacy Policy | Terms of Service