Home >Database >Mysql Tutorial >How Can I Rename Uploaded Files Before Saving Them Using `move_uploaded_file()`?

How Can I Rename Uploaded Files Before Saving Them Using `move_uploaded_file()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 15:43:15441browse

How Can I Rename Uploaded Files Before Saving Them Using `move_uploaded_file()`?

Renaming an Uploaded File Before Saving

While uploading files into a directory using the move_uploaded_file() function, users often encounter the problem of assigning custom names to the uploaded files. To address this issue, here's a solution:

In the provided code, the name of the uploaded file is set when move_uploaded_file() is called. To rename the file to a random number, simply change the second parameter of move_uploaded_file() to the desired filename.

Instead of:

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

Use:

$randNumber = rand(0, 3000); // Generate a random number
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $randNumber . ".extension");

This will assign a random number as the file name while preserving the file's original extension. Additionally, you can use other techniques to generate a unique name based on time, user input, or other criteria.

The above is the detailed content of How Can I Rename Uploaded Files Before Saving Them Using `move_uploaded_file()`?. 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