Saving Files with Desired Name
When uploading and saving files with PHP, you may encounter a scenario where you wish to assign a specific name to the saved file. By default, the server will assign the original filename.
Let's consider the following code:
$target_Path = "images/"; $target_Path = $target_Path.basename($_FILES['userFile']['name']); move_uploaded_file($_FILES['userFile']['tmp_name'], $target_Path);
If you attempt to save the file as "myFile.png" by replacing the following line:
$target_Path = $target_Path.basename($_FILES['userFile']['name']);
with:
$target_Path = $target_Path.basename("myFile.png");
it will not work.
To achieve this, you can extract the extension of the uploaded file and append it to your desired filename:
$info = pathinfo($_FILES['userFile']['name']); $ext = $info['extension']; // get the extension of the file $newname = "newname.".$ext; $target = 'images/'.$newname; move_uploaded_file($_FILES['userFile']['tmp_name'], $target);
By following these steps, you can save the uploaded file with your desired name while maintaining the correct file extension.
The above is the detailed content of How to Save Uploaded Files with a Custom Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!