简体   繁体   中英

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'];;
    }

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? .

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM