Home Backend Development PHP Tutorial Getting Started with PHP: File Uploading and Downloading

Getting Started with PHP: File Uploading and Downloading

May 22, 2023 am 10:51 AM
File Upload Download Document Getting started with php

In web development, file uploading and downloading is a very common requirement. Whether users upload avatars or documents, or administrators ask users to download a file, this function is needed. As a powerful server-side language, PHP naturally provides powerful file operation functions and class libraries, allowing us to easily implement file upload and download functions.

This article will introduce the basic process and common functions to implement file upload and download in PHP, and provide sample code. If you are a PHP beginner or are learning file operations, I hope this article can provide you with some guidance and help.

File upload

In PHP, file upload is implemented through the HTTP protocol, that is, through a form, the user can select a local file and upload it to the server. The functions we need to use are the $_FILES global variable and the move_uploaded_file() function.

First, we need to write an HTML form on the front end. The code is as follows:

<form method="post" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传文件">
</form>
Copy after login

It should be noted that we need to set the method of the form to post, the action to the php file for background processing file upload, and the enctype needs to be set to multipart/form-data to support files Upload.

Next, we write code in the upload.php file in the background to handle file upload. The code is as follows:

<?php
if(isset($_FILES['file'])){
    $file = $_FILES['file'];
    $filename = $file['name'];
    $tmp_name = $file['tmp_name'];
    $target_path = "./uploads/".$filename;
    move_uploaded_file($tmp_name, $target_path);
    echo "文件上传成功";
}
?>
Copy after login

Use if to determine whether a file has been uploaded, and obtain various information about the file from the $_FILES array. $file['name'] represents the file name, $file['tmp_name'] represents the file path of the temporary file. We need to move it to the specified location on the server, assuming it is the "./uploads/" directory, and finally output a successful upload message.

File download

File download means that the user can download a file from the server to the local by clicking a link or button. The functions we need to use are the header() function and readfile() function.

First, we need to set the access permissions of the files on the server so that users can download them. We can set it through the .htaccess file or the configuration file of the web server.

Next, we write HTML code on the front end to generate the download link. The code is as follows:

<a href="download.php?filename=test.pdf">点击下载文件</a>
Copy after login

It should be noted that we need to set the href of the link to the php file downloaded by the background processing file, and also need to bring the file name as a parameter in the link.

Finally, we write code in the download.php file in the background to handle file downloads. The code is as follows:

<?php
if(isset($_GET['filename'])){
    $filename = "./uploads/".$_GET['filename'];
    if(file_exists($filename)){
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="'.basename($filename).'"');
        readfile($filename);
        exit;
    }else{
        echo "文件不存在";
    }
}
?>
Copy after login

Use if to determine whether there is a file name parameter passed in, and generate the absolute path of the file based on the file name. If the file exists, we need to set Content-type to the file type (assumed to be pdf type here) and Content-Disposition to attachment, which means downloading as an attachment and outputting the file content. Finally, add exit to prevent the browser from outputting other content.

Summary

Through the brief introduction of this article, I believe that readers will have a deeper understanding of file upload and download in PHP. It should be noted that both file upload and download operations need to consider security and user experience, such as limiting the size and type of uploaded files, anti-leeching of download links, etc. I hope readers will also pay attention to these details when implementing file operations.

The above is the detailed content of Getting Started with PHP: File Uploading and Downloading. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python opening operation after downloading the file Python opening operation after downloading the file Apr 03, 2024 pm 03:39 PM

Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use PHP functions to upload and download attachments for sending and receiving emails? How to use PHP functions to upload and download attachments for sending and receiving emails? Jul 25, 2023 pm 08:17 PM

How to use PHP functions to upload and download attachments for sending and receiving emails? With the rapid development of modern communication technology, email has become an important way for people to communicate and transmit information in daily life. In web development, we often encounter the need to send and receive emails with attachments. As a powerful server-side scripting language, PHP provides a wealth of functions and class libraries that can simplify the email processing process. This article will introduce how to use PHP functions to upload and download attachments for sending and receiving emails. Email is sent first, we

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to solve Java file upload exception (FileUploadException) How to solve Java file upload exception (FileUploadException) Aug 18, 2023 pm 12:11 PM

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

How to use Hyperf framework for file downloading How to use Hyperf framework for file downloading Oct 21, 2023 am 08:23 AM

How to use the Hyperf framework for file downloading Introduction: File downloading is a common requirement when developing web applications using the Hyperf framework. This article will introduce how to use the Hyperf framework for file downloading, including specific code examples. 1. Preparation Before starting, make sure you have installed the Hyperf framework and successfully created a Hyperf application. 2. Create a file download controller First, we need to create a controller to handle file download requests. Open the terminal and enter

How to trigger file download when clicking HTML button or JavaScript? How to trigger file download when clicking HTML button or JavaScript? Sep 12, 2023 pm 12:49 PM

Nowadays, many applications allow users to upload and download files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download. Everyone knows how to use inputtypefile to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button. This tutorial will teach you various ways to trigger a file download when an HTML button or JavaScript is clicked. Use HTML's <a> tag and download attribute to trigger file download when the button is clicked. Whenever we give the <a> tag

See all articles