How to Rename an Uploaded File Before Saving It
You can upload files into a directory using move_uploaded_file(), which assigns the uploaded file's original name by default.
Renaming File with a Random Number
To rename the file with a random number, modify the second parameter of move_uploaded_file():
<?php $temp = explode(".", $_FILES["file"]["name"]); $newfilename = round(microtime(true)) . '.' . end($temp); move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
This code generates a random number based on the current time and appends the original file extension.
Previous Attempts
Your previous attempts to rename the file were unsuccessful because you failed to update the second parameter of move_uploaded_file(). While you changed $_FILES["file"]["name"] to $fileName, this only affected the variable name, not the file name saved in the directory.
The above is the detailed content of How Can I Rename Uploaded Files Before Saving Them Using PHP?. For more information, please follow other related articles on the PHP Chinese website!