File Renaming Before Saving into a Directory
The question revolves around renaming uploaded files before storing them in a specific directory. The code provided utilizes the move_uploaded_file() function to handle file saving and potentially name setting. The objective is to modify the file name using a random number.
The attempted modification, involving the use of $fileName and its subsequent manipulation, didn't lead to the desired renaming. Instead, the $fileName mechanism will not alter the file name used by move_uploaded_file().
To effectively rename the file with a random number, the following approach can be implemented:
$temp = explode(".", $_FILES["file"]["name"]); $newfilename = round(microtime(true)) . '.' . end($temp); move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
This modified code introduces a new variable, $newfilename, which generates a unique file name using the current time as a basis. The file name is constructed by appending the extension of the original file, retrieved using end($temp). This $newfilename is then employed as the second parameter for move_uploaded_file(), ensuring that the file is stored with the desired random name.
The above is the detailed content of How to Rename Uploaded Files Before Saving Using PHP?. For more information, please follow other related articles on the PHP Chinese website!