Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-16 13:15:03
Original
789 people have browsed it

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);
?>
Copy after login

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);
Copy after login

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!

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