PHP file upload

Posted by retoto on Sat, 15 Jan 2022 07:34:38 +0100

PHP file upload

The concept of file upload: the file is saved from the user's local computer to the directory specified by the server's computer through transmission (Web form).

Principle of file upload:

  1. Add file upload form: the browser requests an HTML script of the server (including file upload form)
  2. The user selects a file locally (click the upload box button)
  3. Users click upload: the file will be transmitted to the server through the Internet of things
  4. The server operating system will save the file to the temporary directory: Yes, it is saved in the temporary file format (tmp format under windows)
  5. The server script starts working: judge whether the file is valid
  6. The server script moves the valid files from the temporary directory to the specified directory

(1). Form making

1). method attribute: the form submission method must be POST, because the file size is required for GET transmission.
2). enctype attribute: form attribute, which is mainly used to standardize the encoding method of form data. Generally, multipart / form data is selected
The optional attribute values are as follows:

valuedescribe
application/x-www-form-urlencodedDefault. Encode all characters before sending (convert spaces to "+" symbols and special characters to ASCII HEX values).
multipart/form-dataNo character encoding. This value is required when using a form with a file upload control.
text/plainConverts spaces to "+" symbols, but does not encode special characters. For GET transfer

3). Upload form: file form

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Single file upload-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="image" />
    <input type="submit" name="btn" value="upload" />
</form>

</body>
</html>

(2). $_FILES details

$_ The predefined variable FILES is specially used to store FILES uploaded by users.

Check it first$_ FILES and$_ What can POST receive.
Thus visible$_ The details of the FILES variable are as follows:
1). The suffix name: is used to keep the actual file name on the computer
2). tmp_name: the temporary path saved by the operating system after the file is uploaded to the server (actually used for later use by PHP)
3). Type: mime (multi-functional Internet Mail Extension) type, which is used to identify the file type of the client in the computer (determine the software)
4). error: the code of file upload, which is used to tell the application software (php) what is wrong with the file receiving process (php will judge the file according to the code later)
5). size: file size (php determines whether it should be retained according to actual needs)

File upload error message description:

from PHP 4.2.0 Start, PHP A corresponding error code will be returned with the file information array.
This code can be used in the file array generated during file upload error Field, that is $_FILES['userfile']['error']. 
 
UPLOAD_ERR_OK
 The value is 0, no error occurs, and the file is uploaded successfully.
 
UPLOAD_ERR_INI_SIZE
 The value is 1, and the uploaded file exceeds php.ini in upload_max_filesize The value of the option limit.
 
UPLOAD_ERR_FORM_SIZE
 The value is 2, and the size of the uploaded file exceeds HTML In the form MAX_FILE_SIZE Option.
MAX_FILE_SIZE yes php A browser side size limiting standard, but W3C No recognition.
 
UPLOAD_ERR_PARTIAL
 The value is 3, and only part of the file is uploaded. Packet loss may be caused by unstable network, or the system may be unsafe.
 
UPLOAD_ERR_NO_FILE
 Its value is 4, and no files are uploaded. Maybe the user clicked upload without selecting the file to upload.
 
UPLOAD_ERR_NO_TMP_DIR
 The value is 6 and the temporary folder cannot be found. PHP 4.3.10 and PHP 5.0.3 introduction. That is, the temporary folder corresponding to the operating system does not exist.
 
UPLOAD_ERR_CANT_WRITE
 With a value of 7, the file write failed. PHP 5.1.0 introduction.
Usually because PHP You do not have permission to move temporary files to the specified directory windows Basically does not exist in, but in linux It often occurs in the system.

(3). Save uploaded file

After the file is uploaded, it will be saved in the$_ In FILES, the form of accessing file information is$_ FILES ['name attribute value'] ['element information']
Save the uploaded file, that is, move the temporary file to the target location. The steps are as follows:
1). Judge whether it is an uploaded file (ensure data security): is_uploaded_file()
2). Moving files: move_uploaded_file()

is_ uploaded_ The file() function determines whether the specified file is uploaded through HTTP POST. If the file given by file is uploaded through HTTP POST, TRUE is returned. This function can be used to ensure that malicious users cannot trick scripts into accessing files that cannot be accessed, such as / etc/passwd. This check is particularly important if the uploaded file may cause its content to be displayed to users or other users of the system. In addition, the result of this function is cached. Use clearstatcache() to clear the cache.

move_ uploaded_ The file() function moves the uploaded file to a new location. If successful, it returns true; otherwise, it returns false. This function has two arguments, move_uploaded_file(file,newloc). The parameter file specifies the file to be moved. The parameter newloc specifies the new location of the file, and the new location must include the name of the file itself. This check is particularly important if the uploaded file may cause its content to be displayed to users or other users of the system. This function is only used for files uploaded through HTTP POST. Note: if the target file already exists, it will be overwritten.

form_upload.html file code:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Single file upload-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="image" />
    <input type="submit" name="btn" value="upload" />
</form>

</body>
</html>

form_upload.php file code:

<?php
header('Content-type:text/html;charset=utf-8');

// 1. Obtain document information
$file = $_FILES['image'];

// 2. Judge whether the file is uploaded
if (is_uploaded_file($file['tmp_name'])){
    // Yes, upload files
    if (move_uploaded_file($file['tmp_name'], 'newplace/'.$file['name'])){
        echo "File saved successfully!";
    } else{
        echo "File saving failed!";
    }
} else{
    // Not upload file
    echo "File upload failed!" . "<br>";
}

(4). Multi file upload

When a product needs to upload multiple pictures for display, you need to upload multiple files
    for one content but different file description: form with the same name
When the product needs to be described with pictures of multiple dimensions, it needs to be uploaded with multiple files
    for different contents, the form names are different: solve problems in batch


Multi file upload$_ Data structure form of FILES variable:

Form with the same name: form the form name into an array, and the five elements corresponding to the file: name and Tmp_name, size, type and error form an array of corresponding numbers. The subscripts of the array elements corresponding to each file upload are the same:

form_ upload. The HTML file code is as follows:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Multi file upload(Same name)-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="images[]" />
    <input type="file" name="images[]" />
    <input type="file" name="images[]" />
    <input type="submit" name="btn" value="Batch upload of files with the same name" />
</form>

</body>
</html>

form_ upload. The PHP file code is as follows:

<?php
header('Content-type:text/html;charset=utf-8');

// View file information
echo "<pre>";
var_dump($_FILES);


Forms with different names: each file will form its own independent array of 5 elements
form_ upload. The HTML file code is as follows:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Multi file upload(Different names)-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="image1" />
    <input type="file" name="image2" />
    <input type="file" name="image3" />
    <input type="submit" name="btn" value="Batch upload of files with different names" />
</form>

</body>
</html>

form_ upload. The PHP file code is as follows:

<?php
header('Content-type:text/html;charset=utf-8');

// View file information
echo "<pre>";
var_dump($_FILES);

Traversal, reading and processing of multi file information

Upload processing method of multiple FILES with the same name: find a way to get an array of five elements corresponding to a file. From$_ The corresponding name \ TMP in FILES_ Name \ size \ error \ type information is retrieved one by one. Then stored in different arrays.

form_upload.html file code:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Multi file upload(Same name)-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="images[]" />
    <input type="file" name="images[]" />
    <input type="file" name="images[]" />
    <input type="submit" name="btn3" value="Batch upload of files with the same name" />
</form>

</body>
</html>

form_upload.php file code:

<?php
header('Content-type:text/html;charset=utf-8');
// Judge whether the element exists and is an array: if there is name, it means a file, and if there are multiple (arrays) of name elements, it means batch upload with the same name
if (isset($_FILES['images']['name']) && is_array($_FILES['images']['name'])) {
    // Traversal construction array elements
    $images = array();  // Store all file information, one element represents one file (array)
    foreach ($_FILES['images']['name'] as $k => $file) {
        $images[] = array(
            'name' => $file,
            'tmp_name' => $_FILES['images']['tmp_name'][$k],
            'type' => $_FILES['images']['type'][$k],
            'error' => $_FILES['images']['error'][$k],
            'size' => $_FILES['images']['size'][$k]
        );
    }
// Execute long pass operation after processing
    foreach ($images as $files) {  // $files is a complete upload file information
        // Find the temporary path and specify the storage path
        if (is_uploaded_file($files['tmp_name'])) {
            // If the file is uploaded, perform the storage operation
            if (move_uploaded_file($files['tmp_name'], 'newplace/' . $files['name'])) {
                echo "File saved successfully!" . "<br>";
            } else {
                echo "File saving failed!" . "<br>";
            }
        } else {
            // Not upload file
            echo "File upload failed!" . "<br>";
        }
    }
}

Upload processing method of multiple FILES with different names: according to the form name$_ FILES can be used directly (you know how many FILES are uploaded in the form). If you are not sure how many FILES are uploaded in the form, it is not suitable to fetch them one by one (the efficiency is not high). You can traverse the array$_ The FILES array is fetched one by one.

form_upload.html file code:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--Multi file upload(Different names)-->
<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="image1" />
    <input type="file" name="image2" />
    <input type="file" name="image3" />
    <input type="submit" name="btn3" value="Batch upload with different name" />
</form>

</body>
</html>

form_upload.php file code:

<?php
header('Content-type:text/html;charset=utf-8');

// Traversal processing of files with different names
foreach ($_FILES as $file){  // $file is a complete upload file information
    // Find the temporary path and specify the storage path
    if(is_uploaded_file($file['tmp_name'])){
        // If the file is uploaded, perform the storage operation
        if (move_uploaded_file($file['tmp_name'], 'newplace/'.$file['name'])){
            echo "File saved successfully!" . "<br>";
        } else{
            echo "File saving failed!" . "<br>";
        }
    } else{
        // Not upload file
        echo "File upload failed!" . "<br>";
    }
}

Effect display:

(5). Function encapsulation

Realize the reuse of upload function code: encapsulate the file upload function
Function: upload files
Condition: condition judgment

  1. Is the document type appropriate? Specify MIME type externally
  2. Where are files stored? External designation
  3. File format restrictions (file suffix)? External qualification
  4. File size limit? External designation

Process:
1). Encapsulate an upload function
2). Judge whether the document is valid
3). Determine whether the save path is valid
4). Judge whether there are errors in the process of uploading the file itself: error
5). Processing of file types: matching through MIME
6). Processing of file format: suffix problem
7). Processing of file size
8). Handling of naming conflict: upload a file with the same name? Chinese in the name?
9). Move to specified directory

Result: file upload is realized
5. Success: the result can be seen later: the path and name of the file need to be returned (stored in the database)
6. Failure: return false, specify the error reason (reference parameter)

form_upload.html file code:

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="POST" enctype="multipart/form-data" action="form_upload.php">
    <input type="file" name="image" />
    <input type="submit" name="btn" value="Single file upload" />
</form>

</body>
</html>

form_upload.php file code:

<?php
header('Content-type:text/html;charset=utf-8');

// PHP file upload function encapsulation function

/*
 * Realize file upload (single file)
 * @param1 array $file,  File information to be uploaded: one dimensional five element array (name\tmp_name\error\size\type)
 * @param2 array $allow_type, MIME types allowed to upload
 * @param3 string $path,  Stored path
 * @param4 string &$error,  If an error occurs, explain the reason
 * @param5 array $allow_format = array(),  File formats allowed to upload
 * @param6 int $max_size = 2000000,  The maximum value allowed to upload, in bytes
 */

// Encapsulate an upload function
function upload_single($file, $allow_type, $path, &$error, $allow_format = array(), $max_size = 2000000)
{
    // Judge whether the document is valid
    if (!is_array($file) || !isset($file['error'])){
        // Invalid file
        $error = 'Not a valid upload file!';
        return false;
    }

    // Judge that the save path is valid
    if (!is_dir($path)){
        // path does not exist
        $error = 'File storage path does not exist!';
        return false;
    }

    // Judge whether the file upload process is wrong
    switch ($file['error']){
        case 1:
        case 2:
            $error = 'The file exceeds the size allowed by the server!';
            return false;
        case 3:
            $error = 'There was a problem uploading the file. Only a part of it was uploaded!';
            return false;
        case 4:
            $error = 'The user has not selected the file to upload!';
            return false;
        case 6:
        case 7:
            $error = 'File saving failed!';
            return false;
    }

    // Determine MIME type
    if (!in_array($file['type'], $allow_type)){
        // This file type does not allow uploading
        $error = 'The current file type does not allow uploading!';
        return false;
    }

    // Judge whether the suffix is allowed
    $ext = ltrim(strrchr($file['name'], '.'), '.');  // Take out the suffix
    if (!empty($allow_format) && !in_array($ext, $allow_format)){
        // Upload not allowed
        $error = 'The format of the current file does not allow uploading!';
        return false;
    }

    // Judge whether the current file size meets the current requirements
    if ($file['size'] > $max_size){
        // The file is too large
        $error = 'The size of the currently uploaded file exceeds the maximum allowed size' . $max_size . 'byte';
        return false;
    }

    // Construct file name to prevent name conflict and Chinese garbled Code: type_ Mm / DD / yy_ Random string$ ext
    $fullname = strstr($file['type'], '/', TRUE) . date('Ymd');
    for ($i = 0; $i < 4; $i++){  // Randomly generated string
        $fullname .= chr(mt_rand(65, 90));
    }
    $fullname .= '.' . $ext;  // Splice suffix

    // This means that the file meets the requirements. Now move the file to the specified directory
    if (!is_uploaded_file($file['tmp_name'])){
        // The file was not uploaded
        return false;
    } else{
        if (move_uploaded_file($file['tmp_name'], $path . '/' . $fullname)){
            // Move succeeded
            return $fullname;
        } else{
            // Move failed
            $error = 'File upload failed!';
            return false;
        }
    }
}

// Provide data
$file = $_FILES['image'];
$allow_type = array('image/jpg', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif');
$path = 'newplace';
$allow_format = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 8000000;

// Call function
if ($filename = upload_single($file, $allow_type, $path, $error, $allow_format = array(), $max_size = 2000000))
{
    echo $filename;
} else{
    echo $error;
}

Effect display:

Topics: PHP