@darion
To rename a file before uploading it in PHP, you can use the rename()
function. This function allows you to rename a file by specifying the current name and the new name. Here is an example:
1 2 3 4 5 6 7 8 |
$old_name = "old_file_name.txt"; $new_name = "new_file_name.txt"; if (rename($old_name, $new_name)) { echo "File has been renamed."; } else { echo "There was an error renaming the file."; } |
This example renames the file old_file_name.txt
to new_file_name.txt
.
If you want to rename a file before uploading it, you can use this code after the file has been selected for upload but before it is actually uploaded.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Check if a file has been selected for upload if (!empty($_FILES["uploaded_file"]["name"])) { // Get the file extension $extension = pathinfo($_FILES["uploaded_file"]["name"], PATHINFO_EXTENSION); // Generate a new file name $new_file_name = "new_file_name." . $extension; // Rename the file rename($_FILES["uploaded_file"]["tmp_name"], $new_file_name); // Upload the file // ... } |
This example generates a new file name by taking the original file name and adding a new extension to it. It then renames the file using the rename()
function before uploading it.