Backend Development 6 min read

Handling File Upload and Download in PHP

This article explains how to implement file upload and download functionality in PHP web applications, covering HTML form setup, server‑side processing, validation, moving uploaded files, and delivering files to browsers with appropriate HTTP headers.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Handling File Upload and Download in PHP

File upload and download are common features in web applications. In PHP development, handling them is relatively straightforward using built‑in functions and specific file‑operation utilities.

1. File Upload

Adding a file upload field in an HTML form

In an HTML form, use the <input type="file"> tag to add a file upload field. For example, to upload an image file you can add the following HTML code:

<code>&lt;form action="upload.php" method="post" enctype="multipart/form-data"&gt;
  &lt;input type="file" name="image"&gt;
  &lt;input type="submit" value="上传"&gt;
&lt;/form&gt;</code>

Receiving and processing the uploaded file on the server

On the server side, write a PHP script that uses the $_FILES superglobal to check for an uploaded file and retrieve its information.

<code>$uploadedFile = $_FILES['image'];
$fileName = $uploadedFile['name'];
$fileType = $uploadedFile['type'];
$fileSize = $uploadedFile['size'];
$tmpFilePath = $uploadedFile['tmp_name'];</code>

Validating file type and size

After receiving the file, validate its MIME type and size to ensure it meets the requirements.

<code>$allowedTypes = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($fileType, $allowedTypes)) {
    echo '只允许上传JPEG、PNG或GIF格式的图片文件';
    return;
}
$maxFileSize = 10 * 1024 * 1024; // 10 MB
if ($fileSize > $maxFileSize) {
    echo '文件大小超过了允许的最大限制';
    return;
}</code>

Moving the uploaded file to the target location

Once validation passes, move the file to a designated directory using move_uploaded_file() .

<code>$uploadDir = 'uploads/';
$targetFilePath = $uploadDir . $fileName;
if (move_uploaded_file($tmpFilePath, $targetFilePath)) {
    echo '文件上传成功';
} else {
    echo '文件上传失败';
}</code>

2. File Download

Providing a download link

In a web page, create a link that points to a PHP script handling the download. For example, to download a PDF named file.pdf :

<code>&lt;a href="download.php?filename=file.pdf"&gt;点击下载文件&lt;/a&gt;</code>

Processing the download request on the server

The download script retrieves the requested filename from the query string.

<code>$filename = $_GET['filename'];</code>

Setting HTTP headers

Set appropriate HTTP headers, such as Content-Type , to indicate the MIME type of the file.

<code>header('Content-Type: application/pdf');</code>

Opening the file and outputting it to the browser

Open the file in binary mode and stream its contents to the client.

<code>$filePath = 'uploads/' . $filename;
$handle = fopen($filePath, 'rb');
if ($handle) {
    while (!feof($handle)) {
        echo fread($handle, 4096);
    }
    fclose($handle);
}</code>

By following these steps, you can implement file upload and download functionality in PHP projects, and further extend the solution with additional validation rules, multi‑file handling, or file listing features.

File UploadWeb DevelopmentPHPfile download
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.