form validation in php

form validation

form validation is used to validate data before being filled in the database.


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

this code will send the submitted data to the current page.

but there is a problem, any hacker can inject client-side scripts into web pages by other users, 

this is called Cross-site scripting (XSS).

It is a type of computer security vulnerability typically found in websites.




for this kind of problem :

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


let's create a form:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name: <input type="text" name="uname">
    <br><br>
    E-mail: <input type="text" name="uemail">
    <br><br>
    Website: <input type="text" name="uwebsite">
    <br><br>
    phone: <input type="text" name="umobile">
    <br><br>
    password: <input type="text" name="upass">
    <br><br>
    
    Comment: <textarea name="ucomment" rows="3" cols="30"></textarea>
    <br><br>
    Gender:
    <input type="radio" name="ugender" value="female">Female
    <input type="radio" name="ugender" value="male">Male
    <input type="radio" name="ugender" value="other">Other
    <br><br>

    <input type="submit" name="save" value="Submit">
</form>



first, make sure the data coming from the form must be correct:
 1. remove spaces from starting and ending from the data
    
    function:
                    trim
 2. convert special characters into HTML entities
     function:
                    htmlspecialchars
 3. remove back slashes 
      function:
                    stripslashes


create a function for correction in data:

function correct($data)
{
            $data=trim($data);
            $data=stripslashes($data);
            $data=htmlspecialchars($data);
}


every time we will use data with correction.



0 Comments