Home > Backend Development > PHP Tutorial > How Can I Rename Uploaded Files in PHP Before Saving Them?

How Can I Rename Uploaded Files in PHP Before Saving Them?

Patricia Arquette
Release: 2024-12-16 06:33:13
Original
533 people have browsed it

How Can I Rename Uploaded Files in PHP Before Saving Them?

How to Rename Uploaded Files Before Saving Them into a Directory

The Issue

When uploading files to a directory using PHP's move_uploaded_file() function, the file's name remains the same as its original name. This can be undesirable when dealing with multiple files with similar names or if you wish to enforce a specific naming convention.

Solution

To rename an uploaded file before saving it, modify the second parameter of move_uploaded_file(). This parameter specifies the destination path and filename. Here's how you can change it:

$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Copy after login

In this example:

  • $temp is an array of parts of the original filename, split at the period.
  • newfilename creates a new filename based on the current time and the extension of the original file.
  • "../img/imageDirectory/" . $newfilename specifies the destination path and the new filename.

This approach ensures that uploaded files receive a unique random name while retaining their original extension.

The above is the detailed content of How Can I Rename Uploaded Files in PHP Before Saving Them?. 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