Home > Backend Development > PHP Tutorial > PHP implements image upload and download

PHP implements image upload and download

高洛峰
Release: 2016-11-21 15:40:24
Original
1218 people have browsed it

The following content of this article talks about how to upload and download images through php

Building a front-end page for uploading files

Here I use the bootstrap front-end framework and fontawesome icon library. The content is very simple, just an image upload box and a submit button , the code is as follows:

<!--form.php-->
<div class="container">
    <form action="upload_del.php" method="post" enctype="multipart/form-data" class="form-horizontal">
        <input type="hidden" name="MAX_FILE_SIZE" value="2097152">
        <div class="btn btn-success fileBox">
            <span>
                <i class="fa fa-file-image-o"></i>
                上传图片
            </span>
            <input type="file" accept="image/*" name="file[]" multiple>
        </div>
        <input type="submit" value="上传" class="btn btn-primary">
    </form>
</div>
Copy after login

Among them:
The hidden field is mainly used to upload the current file size, set to 2M=>2* 1024*1024=>2097152
Set the receiving file type to image format. Multiple images can be uploaded. Pay attention to the name attribute value. When it is file[], the server can receive multiple pictures

Backend server image upload processing

After the file is uploaded to the server from the front end, the server gets the information of the uploaded file and processes it, which mainly includes the following points:

First of all, is there any picture upload? Error, if there is no next step, an error message will be returned

Detect the size of the file uploaded

Detect the file type to see if it is a picture type

Check whether it is a real picture type, some pictures may be fake, for example, we put a Change the extension of the text file to an image type. The above mentioned steps are still done by

Moving the temporary server file to the specified directory

Some people may ask about steps 2 and 3, haven’t our front-end already limited the upload size in the hidden domain? The receiving type of the file is also set. Why does the server still need to verify it? There is a saying that the server should never trust the data passed by the client. Anyone with programming experience knows that we can modify the front-end page structure and content in the browser, and we can also forge data and front-end verification. It just plays a filtering role and cannot be solved once and for all. The server still has to verify the data passed from the front desk. Next, let’s look at the code directly to process the file upload function upload_fun.php:

<?php

/**
 * 获取上传文件信息,处理单文件和多文件上传
 * @return array 上传文件信息
 */
function getFiles()
{
    $i = 0;
    $files=[];
    foreach ($_FILES as $file) {
        if (is_string($file["name"])) {
            $files[$i] = $file;
            $i++;
        } elseif (is_array($file["name"])) {
            foreach ($file["name"] as $key => $val) {
                $files[$i]["name"] = $file["name"][$key];
                $files[$i]["type"] = $file["type"][$key];
                $files[$i]["tmp_name"] = $file["tmp_name"][$key];
                $files[$i]["error"] = $file["error"][$key];
                $files[$i]["size"] = $file["size"][$key];
                $i++;
            }
        }
    }
    return $files;
}

/**
 * 获取文件的扩展名
 * @param $filename:文件名
 * @return string 扩展名
 */
function getExt($filename)
{
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

/**
 * 生成唯一字符串作为文件名
 * @return string 唯一文件名
 */
function getUniName()
{
    return md5(uniqid(microtime(true), true));
}

/**
 * 上传文件主处理模块
 * @param $fileInfo:文件信息
 * @param string $path:上传文件路径
 * @param bool $flag:是否开启验证是否为真实图片
 * @param int $maxSize:文件最大上传大小
 * @param array $allowExt:允许的文件扩展名
 * @return array 信息
 */
function upload_file($fileInfo, $path = "./uploads", $flag = true, $maxSize = 2*1024 * 1024, $allowExt = ["jpeg", &#39;jpg&#39;, &#39;png&#39;, &#39;gif&#39;])
{
    $res = [];
    if ($fileInfo[&#39;error&#39;] == UPLOAD_ERR_OK) {
        $ext = getExt($fileInfo["name"]);
        $uniName = getUniName();
        $dest = $path . "/" . $uniName . "." . $ext;
        //检测上传文件大小
        if ($fileInfo["size"] > $maxSize) {
            $res["msg"] = $fileInfo["name"] . "上传文件过大";
        }
        //上传文件类型
        if (!in_array($ext, $allowExt)) {
            $res["msg"] = $fileInfo["name"] . "非法文件类型";
        }
        //检测是否为真实图片
        if ($flag) {
            if (!getimagesize($fileInfo["tmp_name"])) {
                $res["mes"] = $fileInfo["name"] . "不是真实图片";
            }
        }
        if ($res) return $res;
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        if (!@move_uploaded_file($fileInfo["tmp_name"], $dest)) {
            $res[&#39;msg&#39;] = $fileInfo["name"] . "文件上传失败";
        } else {
            $res["msg"] = $fileInfo["name"] . "文件上传成功";
            $res["dest"] = $dest;
        }
        return $res;
    } else {
        //判断错误信息
        switch ($fileInfo["error"]) {
            case 1:
                $res["mes"] = "上传文件超过php配置文件中upload_max_filesize选项的值";
                break;
            case 2:
                $res["mes"] = "超过了表单MMAX_FILE_SIZE限制的大小";
                break;
            case 3:
                $res["mes"] = "文件部分被上传";
                break;
            case 4:
                $res["mes"] = "没有选择上传文件";
                break;
            case 6:
                $res["mes"] = "没有找到临时目录";
                break;
            case 7:
                $res[&#39;msg&#39;] = "文件写入失败";
                break;
            case 8:
                $res["mes"] = "系统错误";
                break;
        }
        return $res;
    }
}
Copy after login

The server receives the uploaded file and calls the processing file upload function upload_fun. PHP to process:

<?php
//upload_del.php
require_once "upload_fun.php";

$files = getFiles();
foreach ($files as $fileInfo){
    $res = upload_file($fileInfo);
    echo $res["msg"].&#39;<br>&#39;;
    $uploadFiles[] = $res["dest"];
}
$uploadFiles = array_values(array_filter($uploadFiles));
print_r($uploadFiles);
Copy after login

$uploadFiles = array_values(array_filter($uploadFiles)); This sentence is mainly because when uploading multiple files, there may be errors in individual files and the upload fails, causing a certain value in $uploadFiles[] to be a null value. , so we need to filter it and assign it to a new array

Related labels:
php
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