Home  >  Article  >  Backend Development  >  Application of PHP functions in processing file uploads

Application of PHP functions in processing file uploads

WBOY
WBOYOriginal
2024-04-24 14:15:01310browse

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.

 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 "图像上传失败。";
            }
        }
    }
}
?>

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!

Statement:
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