-4

I want people to upload photos on my website, and save each photo as a random file name. I created the upload form. and this is the uploading php function:

if($_FILES['myprofilepicture']['type']!='image/jpeg' && $_FILES['photo']['type']!='image/jpg' && $_FILES['photo']['type']!='image/png'){header("location:wrongfile.php");}else{
$info = pathinfo($_FILES['photo']['name']);
$randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
$target = 'picture/'.$randomfile; $now=time();
move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
header("location:home.php");

the problem is, if there was a picture uploaded with the same filename before, it will get overwritten, I want to improve the code so that if no photo was uploaded with the same file name before->save photo if a photo was uploaded with the same file name before->generate another random string and continue this loop until no photo was previously uploaded with the same name and then save the photo

any help?

user229044
  • 232,980
  • 40
  • 330
  • 338
Angel
  • 146
  • 2
  • 11

1 Answers1

2

Use file_exists() function to check if a file exists:

if($_FILES['myprofilepicture']['type'] != 'image/jpeg' && 
   $_FILES['photo']['type'] != 'image/jpg' && 
   $_FILES['photo']['type'] != 'image/png')
{
    header("location: wrongfile.php");
}
else
{    
    $info = pathinfo($_FILES['photo']['name']);     
    $randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
    $target = 'picture/'.$randomfile; 

    if(!file_exists($target))  //if file doesn't exist
    {       
        $now = time();
        move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
        mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
        header("location:home.php");
    }

}

The if conditional statement in the above piece of code will check if the file already exists, and if not, execute the statements in the block. However, if you want to repeat the process until a unique file path is found, you can use a loop instead:

while(!file_exists($target))  
{       
    # code ...
}

As a sidenote: you're currently inserting user input directly into your SQL query. This is a very bad practice and it makes your query vulnerable to SQL injection. You should stop using the deprecated mysql_* functions and start using PDO or MySQLi.

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150