8

I got this code from w3schools, and tweaked it based on this one: Rename an uploaded file with PHP but keep the extension

Please help, what do I do so that the file extension will not be .tmp When I upload it to a folder on the server.

   <?php
    $filename=$_FILES["file"]["tmp_name"];
    $extension=end(explode(".", $filename));
    $newfilename=$prod .".".$extension;

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 100000))
      {
      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("../img/user_uploaded/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($filename,
          "../img/user_uploaded/" . $newfilename);
          echo "Stored in: " . "../img/user_uploaded/" .$newfilename;
          }
        }
      }
    else
      {
      echo "Invalid file, File must be less than 100Kb in size with .jpg, .jpeg, or .gif file extension";
      }
    ?>
Community
  • 1
  • 1
user225269
  • 10,743
  • 69
  • 174
  • 251
  • 10
    I've think I've read suspense/horror short stories that start with "I got this code from w3schools". – JAL Sep 08 '10 at 06:45

9 Answers9

8
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;

In the above code you are trying to get the temporary file's extension. Instead, you can take the extension of the original filename uploaded by the user.

$filename=$_FILES["file"]["name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;

This will upload your file with the actual file extension.

Snick
  • 1,022
  • 12
  • 29
Mohamed
  • 96
  • 1
6
rename('path/to/file/file.ext', 'path/to/file/newname.ext');

This function is the concatenating of copy and unlink.

Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
4

Try to use this library for image manipulation... maybe is offtopic, but is realy usefull for dealing with images.

WideImage: http://wideimage.sourceforge.net/

For example:

include('path to WideImage.php');

$filename = $_FILES["file"]["name"];
$ext = strtolower(substr(strrchr($filename, '.'), 1)); //Get extension
$image_name = $name . '.' . $ext; //New image name

$image = WideImage::load($_FILES['file']['tmp_name']); //Get image
$image->saveToFile('path/to/image/' . $image_name); //Save image
Wolfy
  • 4,213
  • 8
  • 35
  • 42
2

I disagree with the answer of @Alexander.Plutov. You don't have to save a file, then copy it, then unlink it.

Since you specify the destination file name in your code:

move_uploaded_file($filename, "../img/user_uploaded/" . $newfilename);
echo "Stored in: " . "../img/user_uploaded/" .$newfilename;

all you have is to specify another name instead of $newfilename. If your goal is to replace .tmp extension by something else, you may remove the last four characters (which are always .tmp, set by PHP), then add your own extension.

If you just want to keep the extension given by the user, use:

$friendlyName = $_FILES["file"]["name"];
$extension = substr($friendlyName, strrpos($friendlyName, '.') + 1);

Of course, you have to be aware of the risk of using something posted by the user. What if there is no extension at all, or if it is too long, or if it does not match the real file type (deadly-virus.exe renamed to pretty-image.jpg)?

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
2

Small example you can use rand() function to create random file-name.

$min_rand=rand(0,1000);
$max_rand=rand(100000000000,10000000000000000);
$name_file=rand($min_rand,$max_rand);//this part is for creating random name for image

$ext=end(explode(".", $_FILES["file"]["name"]));//gets extension

move_uploaded_file($_FILES["file"]["tmp_name"],"/new folder/" . $name_file.".".$ext);//actually reponsible for copying file in new folder

$filenameimage="../upload_image/" . $name_file.".".$ext;
$actualimageurl="../upload_image/" . $_FILES["file"]["name"];
Wazy
  • 8,822
  • 10
  • 53
  • 98
  • `rand() ... rand() ... rand()` -- Deeply confused :-S – jensgram Sep 08 '10 at 07:40
  • No matter how huge is the range you use in your random function, it's not 100% secure. You could random the same number twice and override an existing file. –  Jun 06 '13 at 10:34
2

Best way used the pathinfo()

$filename=$_FILES["file"]["name"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$image_name = $yours_new_name.'.'.$ext;
1

This part does rename the file.

move_uploaded_file($filename,"../img/user_uploaded/" . $newfilename);

So the issue is how to set the value of $newfilename. If you have a method to produce this then the issue is solved.

Babak Bandpay
  • 177
  • 6
  • 15
0

Uninitialized variable $prod! This is a major security flaw. Always initialize your variables before using them.

0

You can add datetime to directory where you uploading it's easier. Example:

$date = date("Y-m-d H:i:s");

../img/user_uploaded/$date

But don't but / in the end becouse it changes directory