How to handle file upload in PHP?

WBOY
Release: 2023-05-11 22:32:02
Original
1942 people have browsed it

With the continuous development of Internet technology, the file upload function has become an essential part of many websites. In the PHP language, we can handle file uploads through some class libraries and functions. This article will focus on the file upload processing method in PHP.

1. Form settings

In the HTML form, we need to set the enctype attribute to "multipart/form-data" to support file upload. The code is as follows:

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

Among them, the type attribute of the input tag is "file" and the name attribute is "file", which is used to specify the name of the uploaded file.

2. PHP file upload processing

In PHP, we can use the $_FILES global variable to process file uploads. Assuming that the file uploaded in our form is named "file", then in PHP, you can obtain the uploaded file information through $_FILES['file']. The

$_FILES array contains five elements:

  1. name: The name of the uploaded file.
  2. type: Type of uploaded file.
  3. tmp_name: Temporary storage path of uploaded files.
  4. error: Error code when uploading files.
  5. size: The size of the uploaded file (in bytes).

Next we can use the move_uploaded_file() function to move the uploaded file to the specified folder. The code is as follows:

$target_dir = "uploads/";   //上传文件的目标文件夹
$target_file = $target_dir . basename($_FILES["file"]["name"]);   //上传文件的完整路径
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    echo "文件上传成功!";
} else {
    echo "文件上传失败!";
}
Copy after login

In the above code, the $target_dir variable specifies the target folder of the uploaded file, and the $target_file variable contains the full path of the uploaded file. We can use the move_uploaded_file() function to move temporary files to the specified directory. Returns true if the move was successful, false otherwise.

When uploading files, in order to ensure the security of the files, we need to perform certain checks and filters on the uploaded files. For example, we can use the is_uploaded_file() function to check whether the uploaded file really comes from the client. The code is as follows:

if(is_uploaded_file($_FILES['file']['tmp_name'])){
    //处理上传文件
}else{
    echo "非法的文件上传!";
}
Copy after login

We can also use the getimagesize() function to get the width and height of the uploaded image. The code is as follows:

if (is_uploaded_file($_FILES['file']['tmp_name'])) {
    $image_info = getimagesize($_FILES['file']['tmp_name']);
    echo "图片宽度:".$image_info[0]."<br/>";
    echo "图片高度:".$image_info[1]."<br/>";
    echo "图片类型:".$image_info[2]."<br/>";
} else {
    echo "非法的文件上传!";
}
Copy after login

3. Limit the size of uploaded files

The default limit in PHP is 2M in file size that can be uploaded, but we can also change this by modifying the configuration file or setting it in PHP limit. For example, in the php.ini file, we can set upload_max_filesize and post_max_size to limit the size of uploaded files.

If we want to set the maximum value of uploaded files in PHP, we can use the ini_set() function to modify the settings in php.ini. The code is as follows:

//设置上传文件的最大值为10M
ini_set("upload_max_filesize","10M");
ini_set("post_max_size","10M");
Copy after login

We can also use $_SERVER['CONTENT_LENGTH'] to get the content length in the header information of the client request to determine whether the uploaded file exceeds the specified size. The code is as follows:

if($_SERVER['CONTENT_LENGTH'] > MAX_SIZE){
    echo "上传文件超过了指定大小!";
}
Copy after login

In the front-end part, you can also use the jQuery.uploadFile.js plug-in to limit the size of uploaded files. The code is as follows:

<input type="file" name="file" id="file"/>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/jquery.uploadfile.js"></script>
<script>
    $("#file").uploadFile({
        url: "upload.php",   //处理文件上传的PHP脚本
        maxFileSize: 1024*1024*5,   //最大上传文件的大小,此处为5M
    });
</script>
Copy after login

4. Handling file upload errors

When uploading files, you may encounter some errors. For example, the uploaded file is too large, the uploaded file type is not allowed, the target folder does not exist, etc. We need to handle these errors to improve user experience and file upload effectiveness.

Some error codes are defined in PHP to facilitate our error judgment and processing. For example:

  1. UPLOAD_ERR_OK (0): Upload successful.
  2. UPLOAD_ERR_INI_SIZE(1): The uploaded file exceeds the configuration in php.ini.
  3. UPLOAD_ERR_FORM_SIZE(2): The uploaded file exceeds the value specified by MAX_FILE_SIZE in the form.
  4. UPLOAD_ERR_PARTIAL(3): Only part of the uploaded file was uploaded.
  5. UPLOAD_ERR_NO_FILE(4): No file was uploaded.
  6. UPLOAD_ERR_NO_TMP_DIR(6): Temporary folder not found.
  7. UPLOAD_ERR_CANT_WRITE(7): File writing failed.

We can use switch statements to handle these errors. The code is as follows:

switch ($_FILES['file']['error']) {
    case UPLOAD_ERR_OK:
        //上传成功
        break;
    case UPLOAD_ERR_INI_SIZE:
        echo "上传的文件超过了php.ini中的配置。";
        break;
    case UPLOAD_ERR_FORM_SIZE:
        echo "上传的文件超过了表单中的MAX_FILE_SIZE指定的值。";
        break;
    case UPLOAD_ERR_PARTIAL:
        echo "上传的文件只有部分被上传。";
        break;
    case UPLOAD_ERR_NO_FILE:
        echo "没有文件被上传。";
        break;
    case UPLOAD_ERR_NO_TMP_DIR:
        echo "找不到临时文件夹。";
        break;
    case UPLOAD_ERR_CANT_WRITE:
        echo "文件写入失败。";
        break;
    default:
        echo "未知错误。";
        break;
}
Copy after login

If you want to limit the uploaded file types to certain types, you can use the in_array() function to make a judgment. The code is as follows:

$allowed_types = array('jpg', 'jpeg', 'gif', 'png');   //允许上传的文件类型
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);   //获取文件类型后缀
if (!in_array($ext, $allowed_types)) {
    echo "不允许上传此类型的文件。";
}
Copy after login

5. Summary

File uploading is a common problem in Web development. PHP provides a variety of methods and functions to handle file uploading. In addition to the methods introduced above, we can also use PHP class libraries for file upload processing, such as PHP File Uploader (https://www.github.com/verot/class.upload.php) and FineUploader (https:// fineuploader.com/). No matter which method is used, we need to ensure the security and validity of the uploaded files.

The above is the detailed content of How to handle file upload in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template