PHP Tutorial: Form Processing and Form Validation

Forms and user input

form processing

When processing HTML forms, PHP can automatically make form elements from the HTML page available to PHP scripts.

# form.html 文件代码

<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
 
<form action="welcome.php" method="post">
名字: <input type="text" name="fname">
年龄: <input type="text" name="age">
<input type="submit" value="提交">
</form>
 
</body>
</html>

# welcome.php 文件代码

欢迎<?php echo $_POST["fname"]; ?>!<br>
你的年龄是 <?php echo $_POST["age"]; ?>  岁。

Get data from drop-down menu

Drop down menu radio selection

Use the select tag to set the three options of the drop-down menu. The form uses the GET method to obtain data. If the action attribute value is empty, it means it is submitted to the current script. We can get the value of the drop-down menu through the name attribute of select:

<?php
$q = isset($_GET['q'])? htmlspecialchars($_GET['q']) : '';
if($q) {
    
    
        if($q =='RUNOOB') {
    
    
                echo '菜鸟教程<br>http://www.runoob.com';
        } else if($q =='GOOGLE') {
    
    
                echo 'Google 搜索<br>http://www.google.com';
        } else if($q =='TAOBAO') {
    
    
                echo '淘宝<br>http://www.taobao.com';
        }
} else {
    
    
?>
<form action="" method="get"> 
    <select name="q">
        <option value="">选择一个站点:</option>
        <option value="RUNOOB">Runoob</option>
        <option value="GOOGLE">Google</option>
        <option value="TAOBAO">Taobao</option>
    </select>
    <input type="submit" value="提交">
    </form>
<?php
}
?>

Insert image description here
Insert image description here

Drop-down menu multiple selection

If the drop-down menu is multi-select (multiple="multiple"), we can get it as an array by setting select name="q[]"

<?php
$q = isset($_POST['q'])? $_POST['q'] : '';
if(is_array($q)) {
    
    
    $sites = array(
            'RUNOOB' => '菜鸟教程: http://www.runoob.com',
            'GOOGLE' => 'Google 搜索: http://www.google.com',
            'TAOBAO' => '淘宝: http://www.taobao.com',
    );
    foreach($q as $val) {
    
    
        // PHP_EOL 为常量,用于换行
        echo $sites[$val] . PHP_EOL;
    }
      
} else {
    
    
?>
<form action="" method="post"> 
    <select multiple="multiple" name="q[]">
    <option value="">选择一个站点:</option>
    <option value="RUNOOB">Runoob</option>
    <option value="GOOGLE">Google</option>
    <option value="TAOBAO">Taobao</option>
    </select>
    <input type="submit" value="提交">
    </form>
<?php
}
?>

Insert image description here
Insert image description here

Insert image description here

radio button form

The values ​​of the name attribute in the radio button form are consistent, but the value values ​​are different.

<?php
$q = isset($_GET['q'])? htmlspecialchars($_GET['q']) : '';
if($q) {
    
    
        if($q =='RUNOOB') {
    
    
                echo '菜鸟教程<br>http://www.runoob.com';
        } else if($q =='GOOGLE') {
    
    
                echo 'Google 搜索<br>http://www.google.com';
        } else if($q =='TAOBAO') {
    
    
                echo '淘宝<br>http://www.taobao.com';
        }
} else {
    
    
?><form action="" method="get"> 
    <input type="radio" name="q" value="RUNOOB" />Runoob
    <input type="radio" name="q" value="GOOGLE" />Google
    <input type="radio" name="q" value="TAOBAO" />Taobao
    <input type="submit" value="提交">
</form>
<?php
}
?>

Insert image description here

checkbox checkbox

checkbox A checkbox can select multiple values, somewhat similar to a drop-down menu with multiple selections.

<?php
$q = isset($_POST['q'])? $_POST['q'] : '';
if(is_array($q)) {
    
    
    $sites = array(
            'RUNOOB' => '菜鸟教程: http://www.runoob.com',
            'GOOGLE' => 'Google 搜索: http://www.google.com',
            'TAOBAO' => '淘宝: http://www.taobao.com',
    );
    foreach($q as $val) {
    
    
        // PHP_EOL 为常量,用于换行
        echo $sites[$val] . PHP_EOL;
    }
      
} else {
    
    
?><form action="" method="post"> 
    <input type="checkbox" name="q[]" value="RUNOOB"> Runoob<br> 
    <input type="checkbox" name="q[]" value="GOOGLE"> Google<br> 
    <input type="checkbox" name="q[]" value="TAOBAO"> Taobao<br>
    <input type="submit" value="提交">
</form>
<?php
}
?>

Insert image description here

form validation

We need to consider security when processing PHP forms. In order to prevent hackers and spam, we need to perform data security verification on the form.

Form validation example

Insert image description here

Field Validation rules
name must. +can only contain letters and spaces
E-mail must. + must be a valid email address (contains '@' and '.')
URL Optional. If present, it must contain a valid URL
Remark Optional. Multi-line input fields (text fields)
gender must. Must choose one
  • text field
名字: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
网址: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
  • single button
性别:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>  value="female"><input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>  value="male"><span class="error">* <?php echo $genderErr;?></span>

Preventing XSS attacks: Avoid $_SERVER["PHP_SELF"] being exploited]

The $_SERVER["PHP_SELF"] variable may be used by hackers!

If the form part of the code is written like this:

# test_form.php为当前php脚本名,也可以写成 action="<?php echo $_SERVER["PHP_SELF"]

<form method="post" action="test_form.php">

The user will enter the following address in the browser address bar:

http://www.runoob.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

The above URL will be parsed into the following code and executed:

<form method="post" action="test_form.php/"><script>alert('hacked')</script>

A script tag has been added to the code, and an alert command has been added. This Javascript code will be executed when the page loads (the user will see a pop-up box)

How to avoid $_SERVER["PHP_SELF"] being exploited?

$_SERVER["PHP_SELF"] can be avoided by using the htmlspecialchars() function.

Show error message directory

Scripts have been added to each field that will display error messages if incorrect information is entered. (If the user submits the form without filling in the information, an error message will be output):

<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> 
名字: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
   .
   .
   .

Regular matching: verification email and URL directory

preg_match — perform regular expression matching

grammar:

int preg_match ( string $pattern , string $subject [, array $matches [, int $flags ]] ) 
# 1. 验证名称,检测 name 字段是否包含字母和空格

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "只允许字母和空格"; 
}


# 2. 验证邮件,检测 e-mail 地址是否合法

$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
  $emailErr = "非法邮箱格式"; 
}


# 3. 验证 URL

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "非法的 URL 的地址"; 
}

Collect form data: $_GET & $_POST directories

  • $_GET variable

Information sent from a form with the GET method is visible to everyone (will be displayed in the browser's address bar), and there are limits on the amount of information sent.

  • So this method should not be used when sending passwords or other sensitive information

Because the variables appear in the URL, you can bookmark the page. In some cases this is useful.

  • The HTTP GET method is not suitable for large variable values. Its value cannot exceed 2000 characters
  • $_POST variable

Information sent from a form with the POST method is invisible to anyone (it will not be displayed in the browser's address bar), and there is no limit on the amount of information sent.

  • $_REQUEST variable

The predefined $_REQUEST variable includes GET, _GET,GET , _POST and the contents of $_COOKIE.

The $_REQUEST variable can be used to collect form data sent via GET and POST methods.

Guess you like

Origin blog.csdn.net/a772304419/article/details/133396943