Home  >  Article  >  Backend Development  >  How to Upload and Save Files with a Specific Name in PHP?

How to Upload and Save Files with a Specific Name in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-16 13:15:03709browse

How to Upload and Save Files with a Specific Name in PHP?

Uploading and Saving Files with a Desired Name

This code uses PHP's move_uploaded_file() function to upload images to a specified folder:

<form action="" method="POST" enctype="multipart/form-data">
  <input type="file" name="userFile"><br>
  <input type="submit" name="upload_btn" value="upload">
</form>

<?php
$target_Path = "images/";
$target_Path .= basename($_FILES['userFile']['name']);
move_uploaded_file($_FILES['userFile']['tmp_name'], $target_Path);
?>

Saving Files with a Desired Name

To save the file with a specific name, modify the basename() function as follows:

$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "desired_filename.".$ext;

$target = 'images/'.$newname;
move_uploaded_file($_FILES['userFile']['tmp_name'], $target);

This ensures that the uploaded file is saved with the desired name while retaining its original extension.

The above is the detailed content of How to Upload and Save Files with a Specific Name 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