88

Below is the code I used in order to upload files into a directory. It works fine. My main question is:

move_uploaded_file() is the one that saves the uploaded file into the directory, and it is also my guess that move_uploaded_file() is the one that sets the name for it.

How could I change the name of my file to a random number?

I have tried to do so below:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 100000) && in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {

        $fileName = $temp[0] . "." . $temp[1];
        $temp[0] = rand(0, 3000); //Set to random number
        $fileName;

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

I tried changing variables such as the $_FILES["file"]["name"] and replacing it with the $fileName; variable so that the new name can be stored.

Umair Ayub
  • 19,358
  • 14
  • 72
  • 146
George Edward Portillo
  • 1,059
  • 1
  • 9
  • 12

5 Answers5

188

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • 9
    Better use `microtime()` to generate a timestamp instead of `rand`. If the random value collides with an already used value, the file would be overwritten without warning. – tmh Sep 09 '13 at 19:49
  • 5
    The OP is using `file_exists()`, so if he uses it correctly there's a 0% possibility of this happening. – Ben Fortune Sep 09 '13 at 19:54
  • 1
    was a great and easy to use answer by Ben Fortune. Thank you Ben – user2491321 Jan 04 '15 at 16:17
  • 1
    We can use `time()` too, it's more robust. – Mihir Ujjainwal Feb 25 '15 at 18:34
  • if i want to insert the file _new_ name in the database ? – Mihir Ujjainwal Feb 25 '15 at 18:36
  • 1
    This answer the question but don't handle the file retrieving after it is uploaded. Just using file_exists is good for avoiding to overwrite the file with the same name on uploading. But how do you retrieve this file after? I would rather use an unique ID on the database and store (rename) each uploaded file with this unique ID (In the DB you have on same record the original file name and the unique ID). Retrieve the file by it's unique ID and display/download the file with its file name. How we store the file on the server and how it is shown or downloaded are different things. – Adrian P. Jul 07 '15 at 15:31
  • 1
    @AdrianP. Typically you'd store the file on the disk and save the path to the file along with an identifier in the database. – Ben Fortune Jul 09 '15 at 08:27
  • 1
    As a personal preference: I save the uploaded file on the disk as $file = time().".ext" and save in the database 2 things: $path = "path/to/file".$file and original file name as $file_name. When I retrieve it I replace the $file with the original name ($file_name). The purpose is to avoid any accidental overwrite of this file by the current user or any other user. – Adrian P. Jul 09 '15 at 14:42
  • @BenFortune the last syntax of `move_uploaded_file` misses a `)`. – Nikunj Madhogaria Aug 19 '15 at 15:46
  • @theScorpion Good eye. – Ben Fortune Aug 19 '15 at 15:48
  • @BenFortune Is it a good practice to name files based on unix timestamp *alone* in case of real world applications? What if two users upload two different files at the same time? – Nikunj Madhogaria Aug 19 '15 at 18:35
  • What if I want to rename multiple files like in a multiple files upload? I use md5(basename()) but it gets too big. With your method it renames all files with the same "name" and upload only one file. – madsongr Nov 24 '16 at 18:19
  • if 2 images are uploaded at the same time, only one will be uploaded to the server – Mario Gonzales Flores Oct 09 '19 at 20:32
  • if the file name is like : "name.name.jpg" then its gonna be a problem while using your explode() function , this answer should be currected since its accepted @BenFortune – kakashi senpai Apr 19 '20 at 20:46
  • @kakashisenpai Why? It's only grabbing the extension. – Ben Fortune Apr 20 '20 at 00:20
7

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Prabhagaran
  • 3,620
  • 1
  • 19
  • 19
7
/* create new name file */
$filename   = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension  = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename   = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg

$source       = $_FILES["file"]["tmp_name"];
$destination  = "../img/imageDirectory/{$basename}";

/* move the file */
move_uploaded_file( $source, $destination );

echo "Stored in: {$destination}";
antelove
  • 3,216
  • 26
  • 20
6

You guess correctly. Read the manual page for move_uploaded_file. Set the second parameter to whereever your want to save the file.

If it doesn't work, there is something wrong with your $fileName. Please post your most recent code.

tmh
  • 1,385
  • 2
  • 12
  • 18
1

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

Yehuda Schwartz
  • 3,378
  • 3
  • 29
  • 38