Jump to content

Change name of an uploaded file


xcandiottix

Recommended Posts

If someone uploads a file to my server, currently the file saves under whatever name they assign the file. I figure this could be a bad practice though, so how can I change the file name? Here's my current script:

 

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

 

I'd like to maybe make it incremental if possible... or possibly just a totally random string.

Link to comment
https://forums.phpfreaks.com/topic/195755-change-name-of-an-uploaded-file/
Share on other sites

http://www.php.net/manual/en/function.rename.php

 

bool rename ( string $oldname , string $newname [, resource $context ] )

 

I would also put a mysql table that handles the old file name and new file names, that way you will be able to locate the files (remember to rename the file to something that no one will use such as "sitename_MMDDYYYY_INCREMENTAL.jpg"  even better would be a properly formatted timestamp.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.