Current Location: Home> Latest Articles> Core Techniques for PHP File Upload and Download to Enhance Development Skills

Core Techniques for PHP File Upload and Download to Enhance Development Skills

M66 2025-07-17

PHP File Upload Handling Techniques

File upload is a common and essential feature in web development. PHP uses the $_FILES global variable to receive and manage files. The typical upload process includes the client submitting the file, the server saving it to a temporary directory, validating the file's legitimacy, and finally moving the file to a designated directory to complete the upload.

Example of HTML Upload Form Setup

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload File">
</form>

Parsing Uploaded File Information

<?php
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
?>

File Upload Processing Example Code

<?php
$allowedTypes = ['image/jpeg', 'image/png'];  // Allowed file types
$maxSize = 2 * 1024 * 1024;  // Maximum allowed file size, 2MB

if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
    $destination = 'uploads/' . $fileName;
    move_uploaded_file($fileTmp, $destination);
    echo 'File uploaded successfully!';
} else {
    echo 'File type not allowed or file size exceeds limit!';
}
?>

PHP File Download Handling Techniques

File download is another key function in web applications. The client sends a request, the server reads the file and sends it back in the HTTP response. Proper HTTP headers ensure the file is downloaded and saved correctly.

Example of HTML Download Link

<span class="fun"><a href="download.php?file=filename">Download File</a></span>

File Download Processing Example Code

<?php
$filePath = 'path/to/file/' . $_GET['file'];

if (file_exists($filePath)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($filePath));
    header('Content-Length: ' . filesize($filePath));
    readfile($filePath);
} else {
    echo 'File does not exist!';
}
?>

Summary

By properly validating file types and sizes, and correctly setting file move operations and download headers, you can ensure the security and stability of file uploads and downloads. This article aims to help PHP developers understand the underlying file handling principles and apply them flexibly in real projects.