Home  >  Article  >  Backend Development  >  How to Customize File Names During File Uploads in PHP?

How to Customize File Names During File Uploads in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 01:23:02910browse

How to Customize File Names During File Uploads in PHP?

Customizing File Names during File Uploads

To upload and save files using PHP, you can utilize the provided code. However, if you wish to specify a custom name for the saved file, follow these steps:

  • Extract File Extension: To determine the file's extension (e.g., "png"), use the pathinfo function to extract information about the uploaded file, which you can then store as a variable.
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension'];
  • Create a Custom File Name: Generate a custom file name by combining a string (e.g., "myFile") with the extracted extension.
$newname = "myFile.".$ext;
  • Update Target Path: Modify the target path to reflect the custom file name.
$target = 'images/'.$newname;
  • Move the File: Use the move_uploaded_file function to save the file at the specified target path with the custom name.
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);

By completing these adjustments to your code, you can upload and save files with user-defined names.

The above is the detailed content of How to Customize File Names During File Uploads 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