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.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload File">
</form>
<?php
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
?>
<?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!';
}
?>
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.
<span class="fun"><a href="download.php?file=filename">Download File</a></span>
<?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!';
}
?>
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.