Home >Backend Development >PHP Tutorial >How to Customize File Names During File Upload in PHP?

How to Customize File Names During File Upload in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 07:04:021102browse

How to Customize File Names During File Upload in PHP?

Customizing File Name During File Upload

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.

Customizing Filename with a Static Name

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.

Customizing Filename with a Dynamic Name

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!

Statement:
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