Home >Backend Development >PHP Tutorial >PHP study notes: file upload and download
PHP study notes: file upload and download
Introduction:
In modern network applications, file upload and download are very common functional requirements. Whether users upload pictures, audio, video and other files, or users download resource files provided by the website, file upload and download are one of the essential functions. This article will introduce how to use PHP language to implement file upload and download functions, and provide specific code examples to help readers deeply understand its principles and specific implementation methods.
1. File upload
File upload refers to the process of sending local files to a remote server. It is often used in scenarios where users upload pictures, audio, video and other files. In PHP, file upload mainly relies on the $_FILES global variable and related functions.
1.1 Principle of file upload
The principle of file upload is to send the file content to the server through the POST request of the HTTP protocol, and save the file to the specified directory on the server side. The specific steps are as follows:
1.2 File upload code example
The following is a simple file upload example:
<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload File" name="submit"> </form>
In the above code, we create a form that contains a file selection box and an upload button. The form's enctype attribute is set to "multipart/form-data" to support file uploads. The action attribute of the form specifies the target URL for file upload (here, upload.php).
On the server side, we can use the following code to save uploaded files:
<?php $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; // 检查文件是否已存在 if (file_exists($targetFile)) { echo "Sorry, file already exists."; $uploadOk = 0; } // 检查文件大小 if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // 允许某些文件格式上传 $allowedTypes = array('jpg', 'jpeg', 'png', 'gif'); $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); if (!in_array($fileType, $allowedTypes)) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // 如果上述检查通过,则保存文件 if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) { echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
In the above code, we first define a target directory $targetDir to save uploaded files. Then get the file name uploaded by the user and concatenate it with the target directory to form the final file path $targetFile. A series of checks are performed in the code, such as checking whether the target file exists, file size and allowed file formats, etc. Finally, if the check passes, the temporary file is saved to the target path through the move_uploaded_file function.
2. File Download
File downloading refers to the process of sending files on the remote server to the local client. In PHP, file downloading is mainly achieved by setting HTTP response header information, and using related functions to send the file content to the client.
2.1 Principle of file download
The principle of file download is to tell the browser to process the requested file as a download file by setting the HTTP response header information, rather than opening it directly in the browser. The specific steps are as follows:
2.2 File download code example
The following is a simple file download example:
<?php $filePath = "downloads/file.txt"; $fileName = basename($filePath); // 检查文件是否存在 if (!file_exists($filePath)) { die("File not found."); } // 设置响应头信息 header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename="" . $fileName . """); // 读取文件内容并发送给客户端 readfile($filePath); ?>
In the above code, we first specify the file path to download $filePath, and then Get the file name $fileName. We ensure the downloaded file exists by checking if the file exists. Then, by setting the Content-Type and Content-Disposition response header information, tell the browser to process the requested file as a download file. Finally, use the readfile function to send the file content to the client to complete the file download.
Conclusion:
File uploading and downloading are common functional requirements in PHP development. By understanding the principles of file upload and download, and using relevant functions and code examples, we can quickly implement these functions. I hope this article will help readers upload and download PHP files and further master and apply these technologies.
The above is the detailed content of PHP study notes: file upload and download. For more information, please follow other related articles on the PHP Chinese website!