Reputation: 15
I want to add a 3 digit random number at the front of the uploaded image
if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$random = rand(000,999);
$date = date('Y-m-d H:i:s');
move_uploaded_file($temp,"files/".$name);
$query=$DBcon->query("INSERT INTO upload (name,date) VALUES ('$name','$date')");
if($query){
header("location:index.php");
}
else{
die(mysql_error());
}
}
Upvotes: 1
Views: 1370
Reputation: 2755
You wanted to use a 3 digit random number at the front of the file name. For generating the random number you have used :
$random = rand(000,999);
The above statement will generate random numbers between 0
and 999
, which means not all generated random number will be 3 digits.
You need to pad the random number with 0
to the desired length.
$random = rand(000,999);
$random = str_pad($random, 3, '0', STR_PAD_LEFT);
To use this random number in your file name, prepend it to the filename as below.
$name = $random.$name;
Your completed code should look like this.
if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$random = rand(000,999);
$random = str_pad($random, 3, '0', STR_PAD_LEFT);
$name = $random.$name;
$date = date('Y-m-d H:i:s');
move_uploaded_file($temp,"files/".$name);
$query=$DBcon->query("INSERT INTO upload (name,date) VALUES ('$name','$date')");
if($query){
header("location:index.php");
}
else{
die(mysql_error());
}
}
Upvotes: 1
Reputation: 1237
Instead of:
move_uploaded_file($temp,"files/".$name);
do this:
move_uploaded_file($temp,"files/".$name.$random);
Upvotes: 0
Reputation: 108
if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$random = rand(000,999);
$date = date('Y-m-d H:i:s');
$name=$random.$name;
move_uploaded_file($temp,"files/".$name);
$query=$DBcon->query("INSERT INTO upload (name,date) VALUES ('$name','$date')");
if($query){
header("location:index.php");
}
else{
die(mysql_error());
}
}
Upvotes: 0