Application of PHP functions in processing file uploads

WBOY
Release: 2024-04-24 14:15:01
Original
398 people have browsed it

File upload PHP function: move_uploaded_file(): Move the uploaded file file_exists(): Check whether the file exists is_uploaded_file(): Check whether the file is uploaded through HTTP POST getimagesize(): Get the size and type of the image file mime_content_type(): Get the MIME type of the file

PHP 函数在处理文件上传中的应用

Application of PHP function in file upload

File upload is a common function in Web development. PHP provides a variety of functions to easily handle file upload tasks.

Function

  • move_uploaded_file(): Move the uploaded file from the temporary location to the specified location.
  • file_exists(): Check whether the file exists.
  • is_uploaded_file(): Check if the file was uploaded via HTTP POST.
  • getimagesize(): Get the size and type of the image file.
  • mime_content_type(): Get the MIME type of the file.

Practical Case: File Upload Script

We create a simple script that allows users to upload image files.

<?php
// 检查文件是否存在
if (isset($_FILES["image"])) {
    // 检查文件大小
    if ($_FILES["image"]["size"] > 2097152) {
        echo "文件过大,请上传小于 2MB 的图像。";
    } else {
        // 获取图像信息
        $imageInfo = getimagesize($_FILES["image"]["tmp_name"]);

        // 验证图像类型
        if ($imageInfo[0] > 1920 || $imageInfo[1] > 1920) {
            echo "图像尺寸太大,请上传小于 1920x1920 的图像。";
        } else if (!in_array($imageInfo[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG])) {
            echo "图像格式不支持,请上传 JPEG 或 PNG 格式的图像。";
        } else {
            // 获取 MIME 类型
            $mimeType = mime_content_type($_FILES["image"]["tmp_name"]);

            // 移动文件
            if (move_uploaded_file($_FILES["image"]["tmp_name"], "uploads/" . $_FILES["image"]["name"])) {
                echo "图像上传成功。";
            } else {
                echo "图像上传失败。";
            }
        }
    }
}
?>
Copy after login

The above is the detailed content of Application of PHP functions in processing file uploads. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!