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

How Can I Rename Uploaded Files Before Saving Them to a Directory?

Mary-Kate Olsen
Release: 2024-12-31 05:04:09
Original
682 people have browsed it

How Can I Rename Uploaded Files Before Saving Them to a Directory?

Renaming Uploaded Files Prior to Directory Storage

Your code for uploading files to a directory is efficient. However, you seek to rename the uploaded file using a random number before saving it to the directory.

move_uploaded_file()'s Function

You correctly identified move_uploaded_file() as responsible for saving the uploaded file and potentially setting its name. This function accepts two parameters:

  1. The temporary location of the uploaded file ($_FILES["file"]["tmp_name"])
  2. The target destination, including the file's name in the directory ("../img/imageDirectory/" . $_FILES["file"]["name"])

Renaming the File

To rename the file to a random number, you can modify the second parameter as follows:

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

Here, round(microtime(true)) generates a random number based on the current time, which is then combined with the file's original extension (end($temp)).

Modified Code:

Replace this line in your code:

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
Copy after login

With:

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Copy after login

This modification will rename the uploaded file to a random number while preserving the original file extension.

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