Home > Database > Mysql Tutorial > How to Rename Uploaded Files Before Saving Using PHP?

How to Rename Uploaded Files Before Saving Using PHP?

Barbara Streisand
Release: 2024-12-19 08:55:10
Original
277 people have browsed it

How to Rename Uploaded Files Before Saving Using PHP?

File Renaming Before Saving into a Directory

The question revolves around renaming uploaded files before storing them in a specific directory. The code provided utilizes the move_uploaded_file() function to handle file saving and potentially name setting. The objective is to modify the file name using a random number.

The attempted modification, involving the use of $fileName and its subsequent manipulation, didn't lead to the desired renaming. Instead, the $fileName mechanism will not alter the file name used by move_uploaded_file().

To effectively rename the file with a random number, the following approach can be implemented:

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

This modified code introduces a new variable, $newfilename, which generates a unique file name using the current time as a basis. The file name is constructed by appending the extension of the original file, retrieved using end($temp). This $newfilename is then employed as the second parameter for move_uploaded_file(), ensuring that the file is stored with the desired random name.

The above is the detailed content of How to Rename Uploaded Files Before Saving Using 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