1, PHP foundation - form value transfer and file upload

Form value transfer

  1. Concept:
    Form value transfer means that the browser submits the user's selection or input data to the background server language through form elements.

  2. Why use forms to transfer values?
    The characteristic of dynamic website (Web2.0) is that the background customizes data according to the needs of users. The so-called "demand" is the data information selected or entered by users through the current selection, and the form is the bearer of these data.

  3. Form value transfer method
    GET pass value
    1) Form form

<form method="GET">Form Elements </form>

2) a label

<a href="www.itcast.cn/index.php?subject=PHP">

3) href attribute of location object

<script>location.href="www.itcast.cn/index.php?data=PHP"</script>

4) assign() method of location object

<script>location.assign("www.itcast.cn/index.php?data=PHP")</script>

POST value transfer
1) Basic setting of post form mode

Form element 2) difference between post mode and get mode

1. The data transmitted by get is mainly used to obtain data without changing the resources on the server: get is only used to obtain content
2. The data transmitted by POST is mainly used to increase data and change resources on the server: POST will change the data content on the server
3. In terms of transmission mode, post must use form, while get can use form and URL
4. The data transferred by GET can be visible in the URL, but not in the post: the value transferred by GET will eventually be displayed in the address bar of the browser:? Data name = data value & data name 2 = data value 2
5. The data size that get and post can transmit is different. Get is 2K, and post theory has no limit (in fact, get and post have no data length limit, but the browser manufacturer has made some restrictions)
6. The data formats that get and post can transmit are different: get transmits simple data (numeric value / string), and post can submit complex data (binary, etc.)

Three ways for PHP to receive data
Whether it is$_ GET/$_POST/$_REQUEST, the three are PHP super global (no range limit) predefined arrays. The value of the "name" attribute of the form element is the subscript of the array, and the value corresponding to the value attribute is the element value of the array

$_GET Receiving mode: receiving mode GET Data submitted by 
$_POST Method: receiving POST Data submitted by 
$_REQUEST Method: receiving POST perhaps GET All data submitted 
1)$_REQUEST Content of stored data: $_POST and $_GET Merge and store into an array 
2)$_REQUEST and $_POST And $_GET Contact: if GET and POST There is an array element (subscript) with the same name in, POST Will cover GET(PHP The subscript of the array element is unique), which can be used in php.ini Configure in

GET/POST/REQUEST relationship:

Prove that POST will override GET in REQUEST:

PHP processing checkbox data
How check box form items are named
Check box: usually a kind of content is delivered to the background in the same form (with the same name). Database storage is usually a field storage. Feature of check box: it will be submitted only when it is selected

1. On the browser side, the value of the name attribute of the checkbox will be submitted by the browser without reservation
2. In PHP P O S T / _POST/ P​OST/_GET will overwrite the name attribute with the same name

Solution: the browser doesn't recognize [] (the browser doesn't think it has particularity), but PHP thinks [] has particularity: the system automatically thinks that the symbol is in the form of array, so PHP will automatically combine the elements with the same name but [] to form an array

Check box data receiving form
PHP will automatically combine elements with the same name into an array

PHP processing checkbox data
Common processing of check box data
1) Data processing of radio buttons
Radio button: multiple choices can appear, but only one can be selected
1. For the name attribute used in the form, use the same name: only one can be selected
2. The data received in the background does not need additional processing
3. For database storage, only one field is needed to store ordinary data (number or string)

4. After PHP gets the data, organize SQL to store it directly in the data table
2) Data processing of multiple selection buttons
1. The name attribute in the form uses the array format: name [] (one for a kind of check box data)
2. After the data is received in the background, it is an array (the array cannot be stored in the database)
3. PHP needs to convert the array into a string in the specified format: separate each element with a separator and form a string: implode('separator ', array)

4. PHP organizes SQL to be stored directly into the database

Take out the check box data display
1. If it is the reverse operation, use explode to turn the string into an array after taking out the data

2. In HTML display, check whether the check box has checked = "checked" attribute: in by judging whether the check box element exists in the array_ array()

3) Data processing of other common form items with the same name
Apart from the radio button radio box and checkbox check box, form items with the same name rarely appear. If you have to use a with the same name for management, you can use the checkbox method for operation
1. Add []
2. Array processing when PHP receives
3. Convert PHP to a formatted string
4. Database string storage

Check box details
If the check box is not selected, the browser will not submit. Therefore, when PHP receives and uses check box (radio box) data, it should first determine whether the data exists

File upload
principle
File upload: the file is saved from the user's local computer to the directory specified by the computer where the server is located through transmission (Web form).

1. Add file upload form: the browser requests the HTML script of a 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, in the format of temporary file (tmp 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 (complete)

Form writing
1) Method attribute: the form submission method must be POST
2) enctype attribute: form attribute, which is mainly used to standardize the encoding method of form data

3) Upload form: file form

In PHP, there is a predefined variable$_ FILES is specially used to store FILES uploaded by users.

Test: if there is no enctype attribute, what will the uploaded file look like?
$_ Detailed explanation of FILES variable
1) Name: the actual name of the file on the user (browser side) computer (actually used to retain the suffix)
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 (multifunctional Internet Mail Extension) type, which is used to identify the file type (determine the software) of the client in the computer
4) error: the code of file upload, which is used to inform the application software (PHP) of any problems in the process of receiving files (PHP will judge the files according to the code later)

5) Size: file size (PHP determines whether to keep it according to actual needs)
Move temporary files to destination
After the file is uploaded, it will be saved to F I L E S in , that Do you interview ask writing piece letter interest of shape type Just yes _ In FILES, the form of accessing file information is In F # ILES, the form of accessing file information is_ FILES ['form name attribute value'] ['element information']

1) Judge whether it is an uploaded file: is_uploaded_file()

2) Moving files: move_uploaded_file()


Multi file upload
When the product needs to upload multiple pictures for display: then you need to upload multiple files
For one content but different file description: form with the same name

When the product needs multi-dimensional Picture Description: multi file upload is required
For different contents, the form names are different: solve problems in batch

Multi file upload$_ Data structure form of FILES variable

Batch upload: form with the same name: form the form name into an array, and simultaneously upload the five elements corresponding to the file: name and tmp_name, size, type and error form corresponding arrays. The subscripts of the corresponding array elements uploaded by each file are the same: name[0] and type[0] belong to the same file


Batch upload: forms with different names: each file will form its own independent array of 5 elements

When the product needs to upload multiple pictures for display: then you need to upload multiple files
For one content but different file description: form with the same name

When the product needs multi-dimensional Picture Description: multi file upload is required
For different contents, the form names are different: solve problems in batch

Multi file upload$_ Data structure form of FILES variable

Batch upload: form with the same name: form the form name into an array, and add the five elements corresponding to the file: name
Tmp_name, size, type and error form corresponding arrays. The subscripts of the corresponding array elements uploaded by each file are the same: name[0] and type[0] belong to the same file

Batch upload: forms with different names: each file will form its own independent array of 5 elements


Traversal, reading and processing of multi file information

1. Upload processing method of multiple files with different names: according to the form name F I L E S in take Out come Just can with straight meet send use ( bright Indeed know Avenue surface single in have many less individual writing piece upper pass ) ; as fruit no Indeed set surface single in have many less individual writing piece upper pass , no suitable close Suffer individual go take ( effect rate no high ) , can with through too Times calendar _ FILES can be used directly (know how many FILES are uploaded in the form); If you are not sure how many FILES are uploaded in the form and it is not suitable to get them one by one (the efficiency is not high), you can traverse them F ^ it can be used directly after being taken out of ILES (clearly know how many FILES are uploaded in the form); If you are not sure how many FILES are uploaded in the form and it is not suitable to get them one by one (the efficiency is not high), you can traverse them_ FILES array, take it out one by one to upload FILES


2. Upload multiple FILES with the same name: find a way to get an array of five elements corresponding to a file. From$_ Put the corresponding name \ TMP in FILES_ Name \ size \ error \ type is taken out one by one and stored in different arrays.

Follow up questions on file upload
Realize the reuse of upload function code: encapsulate the file upload function
Function: upload files
Condition: condition judgment
File information to be uploaded: an array of 5 corresponding elements
1. Is the document type appropriate? Specify MIME type externally
2. Where are the files stored? External designation
3. File format restrictions (file suffix)? External limitation
4. File size limit? External designation
Result: file upload is realized
1. Success: the result can be seen later: the path and name of the file need to be returned (stored in the database)
2. Failure: return false, specify the error reason (reference parameter)

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

2) Processing of file types
3) Processing of file format
4) Processing of file size
5) Handling of naming conflicts
Follow up questions on file upload
Realize the reuse of upload function code: encapsulate the file upload function
Function: upload files
Condition: condition judgment
File information to be uploaded: an array of 5 corresponding elements
1. Is the document type appropriate? Specify MIME type externally
2. Where are the files stored? External designation
3. File format restrictions (file suffix)? External limitation
4. File size limit? External designation
Result: file upload is realized
1. Success: the result can be seen later: the path and name of the file need to be returned (stored in the database)
2. Failure: return false, specify the error reason (reference parameter)

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: through MIME matching

6) Processing of file format: the problem of suffix

7) Processing of file size

8) Move to specified directory

8) Handling of naming conflict: upload a file with the same name? What about the Chinese name file?


Full code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form action="12-file_upload_function.php" method="post" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit" name="btn" value="Upload file">
</form>
</body>
</html>
<?php

// PHP file upload function encapsulation function
/*
 * Realize file upload (single)
 * @param0 array $file,File information to be uploaded: TMU / name / error / type (one-dimensional array element)
 * @param1 array $allow_type,MIME type of running upload
 * @param2 string $path,Stored path
 * @param3 string &$error,If there is a reason for the error
 * @param4 array $allow_format = array(),File formats allowed to upload
 * @param5 int $max_size = 2000000 ,Maximum upload allowed
 */
//print_r($_FILES);
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 = 'Is not a valid upload file';
        return false;
    }

    // Judge whether the file storage 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 allowed size of the server';
            return false;
        case 3:
            $error = 'There is a problem in the process of uploading the file. Only part of the file is 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 cannot be uploaded
        $error = 'The current file type cannot be uploaded!';
        return false;
    }

    // Judge whether suffix is allowed
    // Remove suffix
    $ext = ltrim(strrchr($file['name'],'.'), '.');
    if (!empty($allow_format) && !in_array($ext, $allow_format)) {
        // Upload not allowed
        $error = 'The current file format cannot be uploaded!';
        return false;
    }

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

    // Construction file name: type_ Mm / DD / yyyy + random string$ ext
    $fullname = strstr($file['type'],'/',true) . date('YYYYmmdd');
    // Generate random string
    for($i = 0; $i<4; $i++)
    {
        $fullname .= chr(mt_rand(65,90));
    }
    // Patching suffixes
    $fullname .= '.' . $ext;


    // Move to specified directory
    if (!is_uploaded_file($file['tmp_name'])) {
        // The file is not an uploaded file
        $error = 'Error, the file is not an uploaded file!';
        return false;
    }

    if (move_uploaded_file($file['tmp_name'],$path . '/' . $fullname )){
        // success
        return $fullname;
    }else {
        // Move failed
        $error = 'File upload failed!';
        return false;
    }

}


// Provide data
$file = $_FILES['image'];
$path = 'uploads';
$allow_type = array('image/jpg','image/jpeg','image/gif','image/pjpeg');
$allow_format = array('jpg','gif','jpeg');
$max_size = 80000000;

if ($filename = upload_single($file,$allow_type,$path,$error,$allow_format,$max_size))
{
    echo $filename;
}else{
    echo $error;
}

Keywords: PHP

Added by mlcheatham on Tue, 01 Feb 2022 19:30:32 +0200