Home >Backend Development >PHP Tutorial >How to Customize File Names During File Upload in PHP?
When uploading files, it's often desirable to store them with a custom name instead of the original filename. Our PHP script for file upload typically assigns the original filename to the saved file, but let's explore how we can customize it.
One approach is to assign a static filename. You can simply replace the basename() function in your code with a desired filename like so:
$target_Path = $target_Path . "myFile.png";
However, this method limits you to a predefined filename and doesn't consider filename collisions.
A more flexible solution is to use a dynamic filename based on the original file's extension. This allows for both customization and uniqueness:
$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);
This code first extracts the file's extension and then concatenates it to a custom name. The resulting filename is unique and maintains the file's original format.
The above is the detailed content of How to Customize File Names During File Upload in PHP?. For more information, please follow other related articles on the PHP Chinese website!