Home > Article > Backend Development > 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!