In web development, file upload and download are common and essential features. Whether users upload images or documents, or need to download files from the server, backend code plays a key role. This article will explain how to implement file upload and download functionality using PHP, with practical code examples for reference.
File upload is the process of transferring local files to the server. PHP offers built-in functions and variables that make it easy for developers to implement upload features.
First, create a file upload form on the frontend to allow users to select files:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
In upload.php, use the $_FILES superglobal to get the uploaded file info, then move the file from the temporary directory to the desired location:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['file'];
<p>// Get the file name<br>
$filename = $file['name'];</p>
<p>// Get the temporary path<br>
$tmp_path = $file['tmp_name'];</p>
<p>// Specify the save path<br>
$save_path = 'uploads/' . $filename;</p>
<p>// Move the file to the target directory<br>
move_uploaded_file($tmp_path, $save_path);</p>
<p>echo 'File uploaded successfully!';<br>
}<br>
?><br>
Make sure there is a directory on the server to store uploaded files; otherwise, the upload will fail. You can check and create the directory with the following code:
<?php
if (!file_exists('uploads')) {
mkdir('uploads', 0777, true);
}
?>
File download means transferring a file from the server to the user's local computer. PHP achieves secure file downloads by setting appropriate HTTP headers.
In download.php, specify the file path, check if the file exists, then set response headers and output the file content:
<?php
$file_path = 'files/document.pdf';
<p>if (file_exists($file_path)) {<br>
header('Content-Description: File Transfer');<br>
header('Content-Type: application/octet-stream');<br>
header('Content-Disposition: attachment; filename=' . basename($file_path));<br>
header('Content-Length: ' . filesize($file_path));<br>
header('Pragma: public');<br>
header('Expires: 0');</p>
<p>readfile($file_path);<br>
exit;<br>
} else {<br>
die('File does not exist!');<br>
}<br>
?><br>
Ensure the specified download file exists in the corresponding directory on the server, otherwise the user cannot download it successfully.
This article systematically introduces the key steps to implement file upload and download in PHP backend. By using $_FILES to get upload info, move_uploaded_file to save files, and setting HTTP response headers to enable file downloads. The sample code is straightforward and suitable for beginners to understand and apply. Developers can further enhance these features according to practical needs to improve user experience.