Home >Database >Mysql Tutorial >How Can I Rename Uploaded Files to Random Numbers Before Saving in PHP?

How Can I Rename Uploaded Files to Random Numbers Before Saving in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 10:38:11956browse

How Can I Rename Uploaded Files to Random Numbers Before Saving in PHP?

Renaming Uploaded Files Before Saving to a Directory

Question:

In an existing PHP script for uploading files to a directory, is it possible to change the file name to a random number before saving it? The move_uploaded_file() function seems to set the file name, but its current behavior is not desired.

Answer:

To rename the uploaded file to a random number, make an adjustment to the move_uploaded_file() function's second parameter. Instead of using the original file name, generate a new file name using a random number and append the file extension.

Code Modification:

// Get the file extension
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

// Generate a new file name based on the current time
$newfilename = round(microtime(true)) . '.' . $extension;

// Save the file with the new file name
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Explanation:

The round(microtime(true)) function generates a random number with a high precision based on the current time. Appending the file extension ensures that the new file name retains the original file type. By using $newfilename in place of $_FILES"file" in the move_uploaded_file() function, the file will be saved with the renamed random number as its file name.

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