Renaming Uploaded Files Prior to Directory Storage
Your code for uploading files to a directory is efficient. However, you seek to rename the uploaded file using a random number before saving it to the directory.
move_uploaded_file()'s Function
You correctly identified move_uploaded_file() as responsible for saving the uploaded file and potentially setting its name. This function accepts two parameters:
Renaming the File
To rename the file to a random number, you can modify the second parameter as follows:
$temp = explode(".", $_FILES["file"]["name"]); $newfilename = round(microtime(true)) . '.' . end($temp);
Here, round(microtime(true)) generates a random number based on the current time, which is then combined with the file's original extension (end($temp)).
Modified Code:
Replace this line in your code:
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
With:
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
This modification will rename the uploaded file to a random number while preserving the original file extension.
The above is the detailed content of How Can I Rename Uploaded Files Before Saving Them to a Directory?. For more information, please follow other related articles on the PHP Chinese website!