Adding generated random number to image name before upload


I have a cms that uploads data + images to a MySQL database, and I’m trying to add a random number that is generated to the image name before its uploaded.

This is what I have but I’m struggling to add $random1 to the correct bit of the code for it to work.

$random1 = substr(number_format(time() * rand(),0,'',''),0,10);

$target = "imgdata/stock/";
$target = $target . basename( $_FILES['image1']['name']);

$q=mysql_query("insert into stock (stock_Image) values('imgdata/stock/$pic1')") or die (mysql_error());

move_uploaded_file($_FILES['image1']['tmp_name'], $target);

I have tried to add $random1 all over those scripts and havent worked it out.


As I always say echo out the variables as you go to see what they contain as this can give you an indication of what is happening.

You will need to get the extension from somewhere but I would guess you want something along these lines:

$random1 = substr(number_format(time() * rand(),0,'',''),0,10); 

$pic1= $random1 . $_FILES['ext']); // I do not know if there is an ext option in the $files array though!

$target = "imgdata/stock/" . $pic1; 

$q=mysql_query("insert into stock (stock_Image) values($target)") or die (mysql_error());
move_uploaded_file($_FILES['image1']['tmp_name'], $target);  

Thank you Rubble, that worked perfectly.

I have a different script for when the image needs to be changed so will use your method and work it into that.