"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Rename Uploaded Files in PHP Before Saving Them?

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

Published on 2024-12-21
Browse:665

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);

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3