Marko Hirsch
Marko Hirsch

Reputation: 15

Add random number prefix to uploaded image

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

Answers (3)

Vivek
Vivek

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

Babak Asadzadeh
Babak Asadzadeh

Reputation: 1237

Instead of:

move_uploaded_file($temp,"files/".$name);

do this:

move_uploaded_file($temp,"files/".$name.$random);

Upvotes: 0

ASHISH SHARMA
ASHISH SHARMA

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

Related Questions