KPO
KPO

Reputation: 880

How to rename an uploaded file before it is saved?

I am using this snippet below to get the filename and extension, which works, but how can i rename the file so that filename will equal bake23 + the extension of the file.

  $variable = 'baKe23';


  $filename = $_FILES['filename']['name'];
  $ext = $_FILES["filename"]["type"];

Rename if a filename already exists:

       $filename = $_FILES['filename']['name']; 
  $extension = substr($filename, strpos($filename,'.'), 
  strlen($filename)-1);

         $sql="SELECT filename FROM documents WHERE person_id= '$pid'";  

     $result=mysql_query($sql);

    $query = mysql_query($sql) or die ("Error: ".mysql_error());

    if ($result == "")
    {
    echo "";
     }
    echo "";


   $rows = mysql_num_rows($result);

   if($rows == 0)
   {
  print("");

   }
   elseif($rows > 0)
   {
  while($row = mysql_fetch_array($query))
   {

  $existing = $row['filename'];

  print("");
   }

    }

    if ( $filename === $existing ) {
$filename = $rnd_id.strrchr($_FILES['filename']['name'], ".");

   } else {
   $filename = $_FILES['filename']['name'];;
    }

Upvotes: 1

Views: 2183

Answers (2)

hakre
hakre

Reputation: 197712

Get the extension from the submitted filename and add it to your variable:

$filename = basename($filename);
$filename = $variable . (string) strrchr($filename, '.');

Edit: For your edited question, literally:

$filename =  $variable . '.' . $ext;

However, considering I would be uploading an image called banana-smiley.gif, the following would happen:

$filename = 'baKe23.image/gif';

This is not what you want I assume. You should not even rely on $_FILES[*]["type"] at all. What you need to do is inspect each uploaded file (determine the type, validate the type, run a virus checker on the uploaded file).

Question related to this are Secure File Upload and validating it and Is it important to verify that the uploaded file is an actual image file?.

Upvotes: 4

genesis
genesis

Reputation: 50976

$variable = 'baKe23';
$filename = $_FILES['filename']['name'];
$filename = $variable.strrchr($_FILES['filename']['name'], ".");

or

$variable = 'baKe23';
$filename = $_FILES['filename']['name'];
$filename = $variable.".".pathinfo($filename, PATHINFO_EXTENSION);

Upvotes: 3

Related Questions