Home > Backend Development > PHP Tutorial > How to Save Uploaded Files with a Custom Name in PHP?

How to Save Uploaded Files with a Custom Name in PHP?

Barbara Streisand
Release: 2024-11-07 17:31:03
Original
518 people have browsed it

How to Save Uploaded Files with a Custom Name in PHP?

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);
Copy after login

If you attempt to save the file as "myFile.png" by replacing the following line:

$target_Path = $target_Path.basename($_FILES['userFile']['name']);
Copy after login

with:

$target_Path = $target_Path.basename("myFile.png");
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template