PHP interacting with Web pages

Posted by toodi4 on Mon, 03 Jan 2022 06:30:00 +0100

1. Fundamentals of PHP web programming

Interaction between PHP and Web pages

When communicating between the browser of the client and the server, certain procedures or protocols shall be followed. HTTP protocol (i.e. Hypertext Transfer Protocol) is used to browse the WWW;
The process of browsing Web pages is a series of request / response processes: users browse a Web site with a browser, first send a request to a server in the network through the Web address, and request to browse a page; After the server finds this page again, it returns the content of the corresponding page in the response;
In the process of browsing the web page, when the user needs to interact with the server, the data can be transmitted through the HTML page returned by the client browser and the PHP code embedded in the HTML page, and the input content will be transmitted from the client to the server;
PHP is a language running on the server side. After being processed by the PHP program on the server side, the user request information is returned to the client browser;
Example: make a simple interaction example

<html>
<head>
    <title>example</title>
</head>
<body>
<?php
    if($_SERVER['REQUEST_METHOD']=='POST')
    {
        echo "User:".$_POST['name']."<br>";
        echo "password:".$_POST['password']."<br>";
        exit;
    }
?>
<form action="login.php" method="post">
    <p>User:<input type="text" name="name" /></p>
    <p>password:<input type="password" name="password" /></p>
    <p><input type="submit" /></p>
</form>
</body>
</html>

The execution results are as follows:

2. Web form

Web form is a tool that uses HTML form to collect different types of data input by users and send data to the server. It is a platform for users to interact with the server;

2.1 create form

Use the < form > tag and insert < from > and < / form > between HTML tags to create a form;
The basic structure of the form is as follows:

<from name="name" method="method" action="url" enctype="value" target="target" id="id">
    ...... //Inserted form element
</from>

The common attributes of the < from > tag are shown in the following table

The target attribute is shown in the following table

For example, create a form called "register" and submit it to the data processing page check by POST_ in. PHP, the returned information is displayed on the current page;
The code is as follows:

<form name="register" action="check_in.php" method="post" target="_blank">
    ......//Inserted form element
</from>

When using a Web form, you need to specify the behavior attribute action, which is used to specify the processing page for submitting data;

2.2 understanding form elements

Form (from) is composed of form elements. Form elements refer to some element labels in the form. Common element labels include:
Input field label, text field label, selection field label, etc. these elements are used to provide a visual interface for user input;
Example: application of table cell

<html>
<head>
    <title>Application of form elements</title>
<body>
    <form>
        account number:<input name="Username" type="text" ><br>
        password:<input name="Password" type="password" ><br>
        male <input name="Sex" type="radio" value="male"><br>
        badminton <input name="Hobby" type="checkbox"><br>
        <input name="Upload" type="file"><br>
        <input name="Login" type="submit"><br>
        <input name="Girl" type="image"><br>
        <input name="Clean" type="reset"><br>
    </form>
</body>
</head>
</html>

The execution results are as follows:

Table cells generally have name and type attributes. Name refers to the name of the input field, and type refers to the type of the input field. Different form elements can be specified;
The < input type = "" > tag provides a total of always input fields, as shown in the following table

When the form is submitted, the value corresponding to the value attribute of the form element will be transmitted to the server. For the value attribute of the text field, its value is the data entered by the user;

3. Basic method of interaction between PHP and Web pages

3.1 accessing and obtaining Web form data

There are two methods to submit form data: POST method and GET method;
The method of submitting data is determined by the method attribute value of the form < form >;
PHP uses two predefined variables$_ GET and$_ POST obtains the form data submitted by the user$_ GET and$_ POST is an automatic global variable of PHP, which can be used directly in PHP programs;

  • Variable$_ GET is an array variable composed of form data$_ The data submitted by the GET method of the form is saved in GET [], and the "data" key is displayed“
    Is the name of the form element; That is, by the name of the form element (the value of the name attribute)
  • Variable$_ POST is also a data variable, which is used to obtain and save the data, usage and variables submitted by the form in the POST method$_ GET is similar.
$username = $_GET['username']
$username = $_POST['username']

$username indicates the name of the variable receiving the data$_ GET['username '] and$_ POST['username '] represents the received data submitted by GET method and POST method respectively;
username indicates the name of the input domain, which is used to identify which domain value is received;
Therefore, when naming form elements, be careful not to duplicate names to avoid errors in obtaining input values;
Example: simple form example
17-19.php

<html>
<head>
    <title>Example 2</title>
</head>
<body>
<table style="border: 1px solid black" align="center"> <!--The border is 1 Black centered-->
    <tr>
        <td align="left"> <!--Content centered-->
            <form name="form1" action="17-47.php" method="post"> <!--Call 17-47.php-->
                <label for="">use&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Household:</label>
                <input type="text" name="username"><br><br>
                <label for="">dense&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Code:</label> <!--&nbsp; Space-->
                <input type="password" name="password"><br><br>
                <label for="">Confirm password:</label>
                <input type="password" name="repasword"><br><br>
                <label for="">Gender:</label>
                <input type="radio" name="gender" value="male" checked="checked">male
                <input type="radio" name="gender" value="female">female<br><br>
                <label for="">hobby:</label>
                <input type="checkbox" name="interest[]" value="read">read
                <input type="checkbox" name="interest[]" value="E-sports">E-sports
                <input type="checkbox" name="interest[]" value="Rock Climbing">Rock Climbing
                <input type="checkbox" name="interest[]" value="yoga">yoga
                <input type="checkbox" name="interest[]" value="jogging">jogging<br><br
                <label for="">occupation:</label>
                <select name="occup"><option value="doctor">doctor</option>
                    <option value="police">police</option>
                    <option value="businessman">businessman</option>
                    <option value="worker">worker</option>
                    <option value="white collar">white collar</option>
                    <option value="liberal professions">liberal professions</option>
                </select><br><br>
                <input type="submit" type="submit" value="Submit data">
            </form>
        </td>
    </tr>
</table>
</body>
</html>

17-47.php

<?php
    $username = $_POST['username'];     //Get user
    $password = $_POST['password'];     //Get password
    $repassword = $_POST['repassword'];
    $gender = $_POST['gender'];         //Get gender
    $interest = $_POST['interest'];     //Get hobbies
    $occup = $_POST['occup'];           //Get a career

    echo "account number:".$username."<br/>";
    echo "password:".$password."<br/>";
    echo "Gender:".$gender."<br/>";
    echo "hobby:".implode(',',$interest)."<br/>";
    echo "occupation:".$occup."<br/>";
?>

The execution results are as follows:


Results after submission

When outputting hobbies, the implode() function of PHP language is used. The implode() function is to form the hobbies in the saved data elements into a string, separated by the given characters ",";
You can also write php code into HTML
Example: writing PHP code into HTML

<html>
<head>
    <title>Example 2</title>
</head>
<body>
<table style="border: 1px solid black" align="center"> <!--The border is 1 Black centered-->
    <tr>
        <td align="left"> <!--Content centered-->
            <form name="form1" action="" method="post"> <!--Call 17-47.php-->
                <label for="">use&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Household:</label>
                <input type="text" name="username"><br><br>
                <label for="">dense&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Code:</label> <!--&nbsp; Space-->
                <input type="password" name="password"><br><br>
                <label for="">Confirm password:</label>
                <input type="password" name="repassword"><br><br>
                <label for="">Gender:</label>
                <input type="radio" name="gender" value="male" checked="checked">male
                <input type="radio" name="gender" value="female">female<br><br>
                <label for="">hobby:</label>
                <input type="checkbox" name="interest[]" value="read">read
                <input type="checkbox" name="interest[]" value="E-sports">E-sports
                <input type="checkbox" name="interest[]" value="Rock Climbing">Rock Climbing
                <input type="checkbox" name="interest[]" value="yoga">yoga
                <input type="checkbox" name="interest[]" value="jogging">jogging<br><br>
                <label for="">occupation:</label>
                <select name="occup"><option value="doctor">doctor</option>
                    <option value="police">police</option>
                    <option value="businessman">businessman</option>
                    <option value="worker">worker</option>
                    <option value="white collar">white collar</option>
                    <option value="liberal professions">liberal professions</option>
                </select><br><br>
                <input type="submit" type="submit" value="Submit data">
            </form>
        </td>
    </tr>
</table>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $username = $_POST['username'];     //Get user
        $password = $_POST['password'];     //Get password
        $repassword = $_POST['repassword'];
        $gender = $_POST['gender'];         //Get gender
        $interest = $_POST['interest'];     //Get hobbies
        $occup = $_POST['occup'];           //Get a career

        echo "account number:".$username."<br/>";
        echo "password:".$password."<br/>";
        echo "Gender:".$gender."<br/>";
        echo "hobby:".implode(',',$interest)."<br/>";
        echo "occupation:".$occup."<br/>";
    }
?>
</body>
</html>


3.2 effective input of web form data

When the password entered in the above code is empty, the program will run incorrectly, but there is no prompt;
Example: data validation program

<html>
<head>
    <title>Example 2</title>
</head>
<body>
<table style="border: 1px solid black" align="center"> <!--The border is 1 Black centered-->
    <tr>
        <td align="left"> <!--Content centered-->
            <form name="form1" action="" method="post"> <!--Call 17-47.php-->
                <label for="">use&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Household:</label>
                <input type="text" name="username"><br><br>
                <label for="">dense&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Code:</label> <!--&nbsp; Space-->
                <input type="password" name="password"><br><br>
                <label for="">Confirm password:</label>
                <input type="password" name="repassword"><br><br>
                <label for="">Gender:</label>
                <input type="radio" name="gender" value="male" checked="checked">male
                <input type="radio" name="gender" value="female">female<br><br>
                <label for="">hobby:</label>
                <input type="checkbox" name="interest[]" value="read">read
                <input type="checkbox" name="interest[]" value="E-sports">E-sports
                <input type="checkbox" name="interest[]" value="Rock Climbing">Rock Climbing
                <input type="checkbox" name="interest[]" value="yoga">yoga
                <input type="checkbox" name="interest[]" value="jogging">jogging<br><br>
                <label for="">occupation:</label>
                <select name="occupy"><option value="doctor">doctor</option>
                    <option value="police">police</option>
                    <option value="businessman">businessman</option>
                    <option value="worker">worker</option>
                    <option value="white collar">white collar</option>
                    <option value="liberal professions">liberal professions</option>
                </select><br><br>
                <input name="submit" type="submit" value="Submit data">
            </form>
        </td>
    </tr>
</table>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $username = $_POST['username'];     //Get user name
        //If the user name is empty, the prompt message will be output and the program will be interrupted
        if($username == ""){     //Judge whether the user name is empty
            echo "<script>alert('User name cannot be empty, please enter user name!')</script>";   //Pop up information prompt box
            exit;   //The program is interrupted and will not be executed downward
        }
        $password = $_POST['password'];     //Get password
        if($password == ""){     //Determine whether the password is empty
            echo "<script>alert('The password is blank, please enter the password!')</script>";
            exit;
        }
        $repassword = $_POST['repassword'];
        if($password != $repassword){       //Judge whether the two passwords are the same
            echo "<script>alert('The two passwords are inconsistent. Please re-enter the password!')</script>";   //Pop up information prompt box
            exit;   //The program is interrupted and will not be executed downward
        }
        $gender = $_POST['gender'];     //Get gender. The default gender is male
        $interest = $_POST['interest']; //Get hobbies
        if($interest == ""){            //If you don't choose hobbies
            echo "<script>alert('Interest not selected, please select!')</script>";   //Pop up information prompt box
            exit;   //The program is interrupted and will not be executed downward
        }
        echo "User:".$username."<br/>";
        echo "password:".$password."<br/>";
        echo "Gender:".$gender."<br/>";
        echo "hobby:".implode(',',$interest)."<br/>";
        $occupy = $_POST['occupy'];
        echo "occupation:".$occupy."<br/>";
        exit;
    }
?>
</body>
</html>

The execution results are as follows:

In the above example, the conditional statement is used to judge whether the input value is empty;
PHP also provides empty(), is_numeric(),is_null() and other functions to further verify the data submitted by the form;

  • empty() function: check whether the variable has a null value. Null values include empty string, 0, null or false; If it has a null value, return TRUE; Otherwise, false is returned;
  • is_numeric() function: check whether the variable is a number or a numeric string. If yes, it returns TRUE; otherwise, it returns FALSE;
  • is_null function: checks whether the variable is null. It returns TRUE only when the variable violates the definition and the value is null, otherwise it returns FALSE;
  • Example: use function to verify the validity of form data
<html>
<head>
    <title>Example 3</title>
</head>
<body>
    <table style="border: 1px solid black " align="center">
        <tr>
            <td>
                <form action="17-19.phtml" method="POST">
                    <label for="">full name:</label>
                    <input type="text" name="username" /><br><br>
                    <label for="">Age:</label>
                    <input type="text" name="age" /><br><br>
                    <input type="submit" name="sumbit" value="Submit" />
                </form>
            </td>
        </tr>
    </table>
</body>
</html>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $username = $_POST['username'];     //Get name
        if(empty($username)){               //Judge whether the submitted name is empty
            echo "<script>alert('Name cannot be blank, please re-enter!')</script>";     //Pop up message prompt box
            exit;           //The program is interrupted and will not be executed downward
        }
        $age = $_POST['age'];       //Get age
        if(empty($age)){            //Judge whether the age is empty or 0
            echo "<script>alert('Age cannot be blank, please re-enter!')</script>";     //Pop up message prompt box
            exit;                   //The program is interrupted and will not be executed downward
        }
        if(!is_numeric($age)){      //Judge whether the entered age is a number
            echo "<script>alert('Age can only be numeric, please re-enter!')</script>";     //Pop up message prompt box
            exit;           //The program is interrupted and will not be executed downward
        }
        echo "full name:".$username."<br>";
        echo "Age:".$age."year"."<br>";
        exit;
    }
?>

The execution results are as follows:

If the name is blank, the execution result is as follows:

3.3 security verification of web forms

Example: form security vulnerability

<html>
<head>
    <title>Example 4</title>
    <style>
        #wn{
            padding: 50px;                  /*50px from page*/
        }
        #zh {
            width: 200px;height: 200px;     /*Width and height of the table*/
            border: 2px solid black;        /*Border width, solid line, black*/
        }
    </style>
</head>
<body>
    <div id="wn">
        <div id="zh" align="center">
            <form action="17-19.phtml" method="POST">
                <br><label for="">Please enter a message:</label><br/><br/>  <!--<br> Line feed-->
                <textarea name="content" style="height: 80px"></textarea><br/><br/>
                <input type="submit" value="Submit">
            </form>
        </div>
    </div>
</body>
</html>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        echo "The message you entered is:".$_POST['content']."<br>";       //Output message by POST method
        exit;
    }
?>


If the visitor enters the following in the message bar:

<script> while(true)alert("Hello,Wodld!")</script>

Click the "submit" button. At this time, the bar is an executable code, which will be executed in the server section, and a dialog box (bug) will appear in the page, which will make the page unable to browse normally;

In the code of the above example, only a script and a prompt command are added. After the page is loaded, the JavaScript code will be executed and the dialog box will pop up circularly on the page;
Hackers can redirect users to a file on another server. The malicious code in the file can change global variables or submit the form to other addresses to save user data, and even implant Trojans with greater harm;
In order to solve the data security problem of web pages, PHP provides strip_tags() and htmlentities() functions, which can filter form data;

  • strip_tags() function: remove HTML tags and PHP tags from the string;
  • htmlentities() function: convert characters into HTML entities, that is, convert HTML tags and PHP tags into characters and output them in text lines;
    Example: form security
<html>
<head>
    <title>Example 4</title>
    <style>
        #wn{
            padding: 50px;                  /*50px from page*/
        }
        #zh {
            width: 200px;height: 200px;     /*Width and height of the table*/
            border: 2px solid black;        /*Border width, solid line, black*/
        }
    </style>
</head>
<body>
    <div id="wn">
        <div id="zh" align="center">
            <form action="17-19.phtml" method="POST">
                <br><label for="">Please enter a message:</label><br/><br/>  <!--<br> Line feed-->
                <textarea name="content" style="height: 80px"></textarea><br/><br/>
                <input type="submit" value="Submit">
            </form>
        </div>
    </div>
</body>
</html>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        echo "The message you entered is:".htmlentities($_POST['content'],ENT_NOQUOTES,UTF-8)."<br>";       //Output message by POST method
        exit;
    }
?>

The execution results are as follows:

It can be seen from the above example that after filtering with the function htmlentities(), the input JavaScript code is normally output in text form;
Check the security of the input data, and the security of the web page can be effectively guaranteed;

3.4 PHP file upload processing

POST method is often used for file upload and data upload;
During file uploading, the enctype attribute of the form should be set to "multipart / form data", and the code is as follows:

<form name="name" enctype="multipart/form-data" method="method" action="url" target="target">
    ......   //Form Data 
</form>

Using global variables in PHP programs$_ FILES handles file upload$_ FILES is an array containing information about uploaded FILES;

  • $_ FILES['myFile']['name']: the original name of the client file, that is, the file name of the file to be uploaded; myFile is the name attribute value of the file field form element in the form, as follows: < input name = "myFile" type = "file" / >
  • $_ FILES['myFile']['type']: the type of uploaded file, such as "imag/png", which needs to be supported by the browser;
  • $_ FILES['myFile']['size']: the size of the uploaded file, in bytes;
  • $_ FILES['myFile']['tmp_name']: the temporary file name stored on the server after the file is uploaded, which is generally defaulted by the system; Available in PHP Ini upload_ tmp_ Specified in dir option;
  • $_ FILES['myFile']['error']: error code related to file upload;
    The following is a description of the code information:
    UPLOAD_ERR_OK value: 0 - no error occurs, and the file is uploaded successfully;
    UPLOAD_ERR_INI_SIZE value: 1 - the uploaded file size exceeds PHP Ini upload_ max_ The value limited by the filesize option;
    UPLOAD_ERR_FORM_SIZE value: 2 - the size of the uploaded file exceeds Max in the HTML form_ FILE_ The value specified by the size option (input = 'hidden' name = 'MAX_FILE_SIZE' value = 'maximum bytes of attachment' can be specified in the form);
    UPLOAD_ERR_PAREIAL value: 3 - only part of the file is uploaded;
    UPLOAD_ERR_NO_FILE value: 4 - no files are uploaded

After the file is uploaded, it will be stored in the default temporary directory of the server, and the configurable file PHP Ini upload_ tmp_ Set the file in dir option to delete the default temporary saved directory;
After uploading, you need to delete the file from the temporary file or to other places, otherwise it will be deleted naturally;
Whether the file upload is successful. After the script is executed, the files in the temporary directory will be deleted; So after uploading the file, use PHP move_ uploaded_ The file () or copy() function copies or moves the uploaded file to another location, and then the whole process of uploading the file is completed;
move_ uploaded_ The parameters of the file() function are as follows:

move_uploda_file($_FILES['myfile']['tmp_name'],dest_name)

$_ FILES['myfile']['tmp_name'] is the temporary file name stored on the server when uploading files;
dest_name is the name of the target file after the move, and the target file name must contain path information;
If the uploaded file is illegal or cannot be moved for some reason, the function will return FALSE;
Example: upload pictures and Preview

<html>
<head>
    <title>Example 4</title>
    <style>
        #wn{
            padding: 50px;                  /*50px from page*/
        }
        #zh {
            width: 200px;height: 200px;     /*Width and height of the table*/
            border: 2px solid black;        /*Border width, solid line, black*/
        }
    </style>
</head>
<body>
    <div id="wn">
        <div id="zh" align="center">
            <form action="17-19.phtml" method="POST" enctype="multipart/form-data">
                <p><input type="file" name="myfile" value="Select the file to upload" ></p>
                <input type="submit" value="upload" />
            </form>
        </div>
    </div>
</body>
</html>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $name = $_FILES['myfile']['name'];
        $type = strtolower(substr($name,strrpos($name,'.')+1));     //Get the file type and convert it to lowercase
        $allow_type = array('jpg','jpeg','gif','png');                           //Define the type of upload allowed
        //Judge whether similar files are allowed to upload
        if(!in_array($type,$allow_type)){
            //If it is not allowed, the prompt type is wrong and stop the program
            echo "<script>alert('Wrong file type! Please re select!')</script>";
            exit;
        }
        $upload_path = 'time';       //Upload file storage path
        if(!file_exists($upload_path)){      //If the path does not exist
            mkdir("$upload_path",0700);      //Create path, 0700 is the maximum permission
        }
        //Start moving files to the appropriate folder
        $img_name = "time/".$name;
        if(move_uploaded_file($_FILES['myfile']['tmp_name'],$img_name)){
            echo "Picture preview";
            echo "<center><img style='width: 220px;'src='$img_name'></center>";
        }
        else{
            echo "<script>alert('File upload failed! Please upload again!')</script>";
            exit;
        }
    }
?>

The execution results are as follows:
Select the file to upload

Picture preview

Temporary storage directory of files

Conclusion

If this article helps you, give a praise and collect a collection. You are welcome to leave a message and comment;
If there are any mistakes in the article, you are welcome to give advice.

Topics: PHP Front-end html