php form form validation + submit to database

Verification details of php forms

First of all, we process all the data submitted by the user through the htmlspecialchars() function of PHP. Converts special characters to HTML entities. This means that HTML characters such as < and > are replaced with & lt; and & gt. This prevents attackers from injecting HTML or JavaScript Code (cross site scripting attacks) exploit code.

When a user submits a form, we do two things:

Use the PHP trim() function to remove unnecessary characters (such as space, tab, line feed) from the user's input data.

Use the PHP striplashes() function to remove backslashes (\) from user input data

 

Format match

1. Match name

"/^[a-zA-Z ]*$/"

Only spaces and letters are allowed, "^" for the beginning, "$" for the end, [a-zA-Z] for A-Z or A-Z or a character in the space.

The example code is as follows:

<?php

$name = $_POST['name'];
if(!preg_match('/^[a-zA-Z]*$/',$name)){
  echo 'Only letters and spaces are allowed';
}

 

2. Match E-mail

"/([\w-]+\@[\w-]+.[\w-]+)/"

"\ w" matches any word character including underscores. Equivalent to '[A-Za-z0-9_ ]’;

+Match the previous subexpression one or more times;

"-" match "-".

 

3. Match URL

"/\b(?:(?:https?|ftp):\/\/|www.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i"

Keep values in form

After the user clicks the submit button, to ensure that the field value is entered correctly, we add PHP script in the input element of HTML, with the names of each field: name, email, and website. In the textarea field of the comment, we put the script between the < textarea > and < / textarea > tags. The PHP script output values are: $name, $email, $website, and $comment variables.

 

The code of a complete PHP form validation instance is as follows:

<!DOCTYPE HTML>

<html>

  <head>

    <meta charset="utf-8">

    <title>form</title>

    <style>

      .error {color: #FF0000;}

    </style>

  </head>

  <body>

  <?php

  // Define variable and set to null by default

  $nameErr = $emailErr = $genderErr = $websiteErr = "";

  $name = $email = $gender = $comment = $website = "";

  if ($_SERVER["REQUEST_METHOD"] == "POST")

  {

    if (empty($_POST["name"]))

    {

      $nameErr = "Name is required";

    }

    else

    {

      $name = test_input($_POST["name"]);

      // Check if the name contains only letters and spaces

      if (!preg_match("/^[a-zA-Z ]*$/",$name))

      {

        $nameErr = "Only letters and spaces are allowed";

      }

    }

    if (empty($_POST["email"]))

    {

      $emailErr = "Mailbox is required";

    }

    else

    {

      $email = test_input($_POST["email"]);

      // Check whether the mailbox is legal

      if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))

      {

        $emailErr = "Illegal mailbox format";

      }

    }

    if (empty($_POST["website"]))

    {

      $website = "";

    }

    else

    {

      $website = test_input($_POST["website"]);

      // testing URL Is the address legal

      if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))

      {

        $websiteErr = "Illegal URL Address of";

      }

    }

    if (empty($_POST["comment"]))

    {

      $comment = "";

    }

    else

    {

      $comment = test_input($_POST["comment"]);

    }

    if (empty($_POST["gender"]))

    {

      $genderErr = "Gender is required";

    }

    else

    {

      $gender = test_input($_POST["gender"]);

    }

  }

  function test_input($data)

  {

    $data = trim($data);

    $data = stripslashes($data);

    $data = htmlspecialchars($data);

    return $data;

  }

  ?>

  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

    //name: <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>

    //website: <input type="text" name="website" value="<?php echo $website;?>">

    <span class="error"><?php echo $websiteErr;?></span>

    <br><br>

    //remarks: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>

    <br><br>

    //Gender:

    <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>  value="female">female

    <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>  value="male">male

    <span class="error">* <?php echo $genderErr;?></span>

    <br><br>

    <input type="submit" name="submit" value="Submit">

  </form>

  <?php

  echo "<h2>What you have entered is:</h2>";

  echo $name;

  echo "<br>";

  echo $email;

  echo "<br>";

  echo $website;

  echo "<br>";

  echo $comment;

  echo "<br>";

  echo $gender;

  ?>

</body>

</html>

The results are as follows:

 

 

These will show you how to handle PHP forms safely. Proper verification of HTML form data is very important to prevent hackers and spam!

 

How can php forms be submitted to the database? (detailed explanation)

Use php to create a simple database and table, and create MySql database and table. For example, to create a test database, the code of the example is as follows:

<?php
//Create connection
$conn = new mysqli('localhost','root','123456');
//Test connection
if($conn->connect_error){
    die('Connection failed:'.$conn->connect_error);
}
//Create database
$sql = 'CREATE DATABASE test';
if($conn->query($sql) === TRUE){
    echo 'Database created successfully';
}else{
    echo 'Database creation failed:'.$conn->error;
}
$conn->close();

The results are as follows:

 

 

Then use the CREATE TABLE statement to create a MySQL table, and set the following fields.

id: it is unique, of type int, and the primary key is selected.

uesrname: user name, type varchar, length 30.

Password: password, type varchar, length 30.

Confirm: confirm the password. The type is varchar and the length is 30.

email: mailbox, type: varchar, length: 30.

<?php
//Create connection
$conn = new mysqli('localhost','root','123456','test');
//Test connection
if($conn->connect_error){
    die('Connection failed:'.$conn->connect_error);
}
//Create data table
$sql = "CREATE TABLE login(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
confirm VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8";

if($conn->query($sql) === TRUE){
    echo 'Data table created successfully';
}else{
    echo 'Data table creation failed:'.$conn->error;
}
$conn->close();

The results are as follows:

 

 

Next, build a simple front-end page for form registration. The form page here is very simple. There are several simple text boxes, such as user name, password, password confirmation, registration mailbox, etc. Its code is as follows:

<!DOCTYPE HTML>

<html>

  <head>

    <meta charset="utf-8">

    <title>form</title>

<style type="text/css">

    *{margin:0px;padding:0px;}

    ul{

      width:400px;

      list-style:none;

      margin:50px auto;

    }

    li{

      padding:12px;

      position:relative;

    }

    label{

      width:80px;

      display:inline-block;

      float:left;

      line-height:30px;

    }

    input[type='text'],input[type='password']{

      height:30px;

    }

    img{

      margin-left:10px;

    }

    input[type="submit"]{

      margin-left:80px;

      padding:5px 10px;

    }

  </style>

  </head>

  <body>

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

  <ul>

    <li>

      <label>user name:</label>

      <input type="text" name="username" placeholder="Please enter your account number"/>

    </li>

    <li>

      <label>password:</label>

      <input type="password" name="password" placeholder="Please input a password" />

    </li>

    <li>

      <label>Confirm password:</label>

      <input type="password" name="confirm" placeholder="Please enter the password again" />

    </li>

    <li>

      <label>Email:</label>

      <input type="text" name="email" placeholder="Please enter email"/>

    </li>

    <li>

      <input type="submit" value="register" />

    </li>

  </ul>

</form>

</body>

</html>

The page is as follows:

 

 

Save the data submitted in the form into variables, and then judge the password and verification code. After all are correct, save the user information into the database and extract and print all the data in the table where the database stores the user information.

<?php

session_start();
header('Content-Type:text/html;charset=utf-8');
$link = mysqli_connect('localhost','root','123456','test');
if(!$link){
    die('connection failed'.mysqli_connect_error());
}

//receive data 
$username = $_POST['username'];
$password = $_POST['password'];
$confirm = $_POST['confirm'];
$email = $_POST['email'];

//Inspection data
if($username == '' || $password == '' || $confirm == '' || $email == ''){
    echo "<script>alert('Information cannot be empty');window.location.href='test.php'</script>";
}elseif((strlen($username) < 3) || (!preg_match('/^\w+$/',$username))){//user name
    echo "<script>alert('The user name is not less than 3 digits and does not contain illegal characters. Please fill in again');window.location.href='test.php'</script>";
}elseif(strlen($password) < 5){//password
    echo "<script>alert('Password no less than 5 digits, please fill in again');window.location.href='test.php'</script>";
}elseif($password != $confirm){//Repeat password
    echo "<script>alert('The two passwords are inconsistent, please fill in again');window.location.href='test.php'</script>";
}elseif(!preg_match('/^[\w\.]+@\w+\.\w+$/i',$email)){//mailbox
    echo "<script>alert('Email is illegal, please fill in again');window.location.href='test.php'</script>";
}elseif(mysqli_fetch_array(mysqli_query($link,"select * from login where username = '$username'"))){//repeat of user name
    echo "<script>alert('User name already exists');window.location.href='test.php'</script>";
}else{

    //insert database
    $sql = "insert into login(username,password,confirm,email) values('$username','$password','$confirm','$email')";
    if(mysqli_query($link,$sql)){
        echo 'login was successful';
    }else{
        echo "<script>alert('login has failed');window.location.href='test.php'</script>";
    }
}

The results are as follows:

Tags: PHP Database SQL ftp

Posted on Sun, 24 May 2020 22:02:21 -0400 by sgiandhu