hi
can any one tell me how validation can be done in PHP WITH OUT USINGjavascript

Recommended Answers

All 10 Replies

yes you can validate in php only,
For example, validate against the blank field like -
if($str ==''){ echo "You have not entered anything";}
or you can use the regular expressions for checking the correct format of data like format of email id etc.
and size exceeding more than 100 char as -
if(strlen($str) >100) { echo "exceeding the limit of 100 chars"; }
etc.

Thank you so much for the reply.... you solved it :)

Hey.

The isset and empty functions are also handy when validating form data. (or any data, for that matter)

thanks Alti.. but i didnt understand your second answer properly

Duplicate... The quick-reply thing keeps doing that :-/

thanks Alti.. but i didnt understand your second answer properly

don't worry about it, it happens because of the quick reply and the reload.

Yes, sorry about that second post. When I posted my first post it got posted twice because of a bug in the forum. (I assume)
It has been removed now.

But OK, as form validation is a rather important topic, let me be a little more thorough.

There are a few steps that are necessary when validating incoming user data.

  1. First step is to eliminate the possibility that the ancient magic_quotes feature is messing up your data. (Ideally, it should be turned off. But it is always best to add this just in case.)
    A few simple lines of code can completely nullify that effect, if it is present.
    Keep in mind that this code should only be executed once per page, or you risk messing up your data even further.
    // Nullify the effects of the magic_quotes feature, if enabled.
    // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed.
    if(get_magic_quotes_gpc()) 
    {
        foreach($_POST as &$_data) 
        {
            $_data = stripslashes($_data);
        }
    }
  2. Verify that all the fields you need are present and filled in.
    In these examples I'll assume you want to verify user login data, where a user passes both his user-name and an email, as well as his password.
    // List all fields you are expecting to get
    $fields = array('username', 'email', 'password');
    
    // Set up an array to contain all errors that occur during the validation.
    // This can then be used later on to determine whether or not the validation failed.
    $errors = array();
    
    // Step through the list of expected fields and verify that they are set, and that they are not empty.
    foreach($fields as $_field) 
    {
        if(!isset($_POST[$_field]) || empty($_POST[$_field])) 
        {
            $errors[] = "Field '$_field' is missing or empty.";
        }
    }
  3. Verify the data in individual fields. As opposed to the previous code example, which only verified their existence, this one verifies that the data you are receiving is in valid format.
    // Verify the username.
    $usernameRegexp = '/[\w\d_-\' ]{3,32}/i';
    if(!preg_match($passwordRegexp, $_POST['username']))
    {
        $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (').";
    }
    
    // Verify the password.
    if(strlen($_POST['password']) < 6)
    {
        $errors[] = "Passwords must be more than 6 characters";
    }
    
    // Verify the email
    $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i';
    if(!preg_match($emailRegexp, $_POST['email']))
    {
        $errors[] = "The email address is invalid!";
    }
  4. And finally, use the $errors array to determine if the validation failed or succeeded:
    // Check if there were any errors
    if(count($errors) == 0) 
    {
        // The data is valid.
        // Do with it as you please.
    }
    else
    {
        // Print all the errors.
        echo "<p>The following errors were found:<br><ul>"
        foreach($errors as $_error)
        {
            echo "<li>$_error</li>";
        }
        echo "</ul><p>";
    }

Put that all together and you will have a pretty decent user-login validation script.


Also, while I'm at it. If you were planing on using the data in that form to log a user in via a SQL query, further security measures need to be taken.

  1. One of the biggest threat to PHP security is SQL Injection.
    This is what the now deprecated magic_quotes feature was meant to prevent, but it was only ever partially effective, and it causes far to much trouble to be wort using.

    There are several ways to prevent this, most of them database-specific. MySQL databases, for example, have the mysql_real_escape_string function, which takes care of escaping the data for you.
    You could use that on the data in the previous examples like so:

    // Prepare all fields for being used in a MySQL query.
    $safeData = array();
    foreach($fields as $_field) {
        $safeData[$_field] = mysql_real_escape_string($_POST[$_field]);
    }
  2. Hash your passwords!
    A basic way to protect your user's passwords from being known by others, including you, is to use a one-way encryption algorithm on it, known as "hashing", to turn it into a long string of seemingly random characters.
    Then you store the hash in the database as the user's password. When it comes time to log the user in, you hash the password he provides in the same way you did when it was created, and compare the two. If the hashes match, it is valid.
    // Create a password hash. Never store passwords as plain text!
    $passwordHash = hash("sha256", $safeData['password']);
  3. And then you create and execute the query, using the now secure data.
    // Compile the query, using the verified data
    $sql = "SELECT `id` 
            FROM   `user` 
            WHERE   
                (`username` = '{$safeData['username']}')
            AND (`email` = '{$safeData['email']}')
            AND (`passwordHash` = '{$passwordHash}')";
  4. Which you would finish of like so:
    // Execut the query and check the results.
    $result = mysql_query($sql);
    if($result && mysql_num_rows($result) == 1)
    {
        echo "Login succesfull!";
        
        // And then do stuff to actually log him in.
    }
    else
    {
        echo "Login failed! Better luck next time.";
    }

I'll leave it there... for now :)

commented: help full +1

hi thanks Alti....:)

Yes, sorry about that second post. When I posted my first post it got posted twice because of a bug in the forum. (I assume)
It has been removed now.

But OK, as form validation is a rather important topic, let me be a little more thorough.

There are a few steps that are necessary when validating incoming user data.

  1. First step is to eliminate the possibility that the ancient magic_quotes feature is messing up your data. (Ideally, it should be turned off. But it is always best to add this just in case.)
    A few simple lines of code can completely nullify that effect, if it is present.
    Keep in mind that this code should only be executed once per page, or you risk messing up your data even further.
    // Nullify the effects of the magic_quotes feature, if enabled.
    // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed.
    if(get_magic_quotes_gpc()) 
    {
        foreach($_POST as &$_data) 
        {
            $_data = stripslashes($_data);
        }
    }
  2. Verify that all the fields you need are present and filled in.
    In these examples I'll assume you want to verify user login data, where a user passes both his user-name and an email, as well as his password.
    // List all fields you are expecting to get
    $fields = array('username', 'email', 'password');
    
    // Set up an array to contain all errors that occur during the validation.
    // This can then be used later on to determine whether or not the validation failed.
    $errors = array();
    
    // Step through the list of expected fields and verify that they are set, and that they are not empty.
    foreach($fields as $_field) 
    {
        if(!isset($_POST[$_field]) || empty($_POST[$_field])) 
        {
            $errors[] = "Field '$_field' is missing or empty.";
        }
    }
  3. Verify the data in individual fields. As opposed to the previous code example, which only verified their existence, this one verifies that the data you are receiving is in valid format.
    // Verify the username.
    $usernameRegexp = '/[\w\d_-\' ]{3,32}/i';
    if(!preg_match($passwordRegexp, $_POST['username']))
    {
        $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (').";
    }
    
    // Verify the password.
    if(strlen($_POST['password']) < 6)
    {
        $errors[] = "Passwords must be more than 6 characters";
    }
    
    // Verify the email
    $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i';
    if(!preg_match($emailRegexp, $_POST['email']))
    {
        $errors[] = "The email address is invalid!";
    }
  4. And finally, use the $errors array to determine if the validation failed or succeeded:
    // Check if there were any errors
    if(count($errors) == 0) 
    {
        // The data is valid.
        // Do with it as you please.
    }
    else
    {
        // Print all the errors.
        echo "<p>The following errors were found:<br><ul>"
        foreach($errors as $_error)
        {
            echo "<li>$_error</li>";
        }
        echo "</ul><p>";
    }

Put that all together and you will have a pretty decent user-login validation script.


Also, while I'm at it. If you were planing on using the data in that form to log a user in via a SQL query, further security measures need to be taken.

  1. One of the biggest threat to PHP security is SQL Injection.
    This is what the now deprecated magic_quotes feature was meant to prevent, but it was only ever partially effective, and it causes far to much trouble to be wort using.

    There are several ways to prevent this, most of them database-specific. MySQL databases, for example, have the mysql_real_escape_string function, which takes care of escaping the data for you.
    You could use that on the data in the previous examples like so:

    // Prepare all fields for being used in a MySQL query.
    $safeData = array();
    foreach($fields as $_field) {
        $safeData[$_field] = mysql_real_escape_string($_POST[$_field]);
    }
  2. Hash your passwords!
    A basic way to protect your user's passwords from being known by others, including you, is to use a one-way encryption algorithm on it, known as "hashing", to turn it into a long string of seemingly random characters.
    Then you store the hash in the database as the user's password. When it comes time to log the user in, you hash the password he provides in the same way you did when it was created, and compare the two. If the hashes match, it is valid.
    // Create a password hash. Never store passwords as plain text!
    $passwordHash = hash("sha256", $safeData['password']);
  3. And then you create and execute the query, using the now secure data.
    // Compile the query, using the verified data
    $sql = "SELECT `id` 
            FROM   `user` 
            WHERE   
                (`username` = '{$safeData['username']}')
            AND (`email` = '{$safeData['email']}')
            AND (`passwordHash` = '{$passwordHash}')";
  4. Which you would finish of like so:
    // Execut the query and check the results.
    $result = mysql_query($sql);
    if($result && mysql_num_rows($result) == 1)
    {
        echo "Login succesfull!";
        
        // And then do stuff to actually log him in.
    }
    else
    {
        echo "Login failed! Better luck next time.";
    }

I'll leave it there... for now :)

That was nice Atli... I need to learn how to create that custom regex codes. May be a link to some tutorial can be helpful..

Yes, sorry about that second post. When I posted my first post it got posted twice because of a bug in the forum. (I assume)
It has been removed now.

But OK, as form validation is a rather important topic, let me be a little more thorough.

There are a few steps that are necessary when validating incoming user data.

  1. First step is to eliminate the possibility that the ancient magic_quotes feature is messing up your data. (Ideally, it should be turned off. But it is always best to add this just in case.)
    A few simple lines of code can completely nullify that effect, if it is present.
    Keep in mind that this code should only be executed once per page, or you risk messing up your data even further.
    // Nullify the effects of the magic_quotes feature, if enabled.
    // This is targeted only at the $_POST array. You can change it to $_REQUEST if needed.
    if(get_magic_quotes_gpc()) 
    {
        foreach($_POST as &$_data) 
        {
            $_data = stripslashes($_data);
        }
    }
  2. Verify that all the fields you need are present and filled in.
    In these examples I'll assume you want to verify user login data, where a user passes both his user-name and an email, as well as his password.
    // List all fields you are expecting to get
    $fields = array('username', 'email', 'password');
    
    // Set up an array to contain all errors that occur during the validation.
    // This can then be used later on to determine whether or not the validation failed.
    $errors = array();
    
    // Step through the list of expected fields and verify that they are set, and that they are not empty.
    foreach($fields as $_field) 
    {
        if(!isset($_POST[$_field]) || empty($_POST[$_field])) 
        {
            $errors[] = "Field '$_field' is missing or empty.";
        }
    }
  3. Verify the data in individual fields. As opposed to the previous code example, which only verified their existence, this one verifies that the data you are receiving is in valid format.
    // Verify the username.
    $usernameRegexp = '/[\w\d_-\' ]{3,32}/i';
    if(!preg_match($passwordRegexp, $_POST['username']))
    {
        $errors[] = "Usernames must be between 3 and 32 characters long, and they may only contain letters, numbers, spaces, and the following characters: (_), (-), (').";
    }
    
    // Verify the password.
    if(strlen($_POST['password']) < 6)
    {
        $errors[] = "Passwords must be more than 6 characters";
    }
    
    // Verify the email
    $emailRegexp = '/^([\w\d.-_]+?)@([\w\d.-_]+?)\.(\w{2,4})$/i';
    if(!preg_match($emailRegexp, $_POST['email']))
    {
        $errors[] = "The email address is invalid!";
    }
  4. And finally, use the $errors array to determine if the validation failed or succeeded:
    // Check if there were any errors
    if(count($errors) == 0) 
    {
        // The data is valid.
        // Do with it as you please.
    }
    else
    {
        // Print all the errors.
        echo "<p>The following errors were found:<br><ul>"
        foreach($errors as $_error)
        {
            echo "<li>$_error</li>";
        }
        echo "</ul><p>";
    }

Put that all together and you will have a pretty decent user-login validation script.


Also, while I'm at it. If you were planing on using the data in that form to log a user in via a SQL query, further security measures need to be taken.

  1. One of the biggest threat to PHP security is SQL Injection.
    This is what the now deprecated magic_quotes feature was meant to prevent, but it was only ever partially effective, and it causes far to much trouble to be wort using.

    There are several ways to prevent this, most of them database-specific. MySQL databases, for example, have the mysql_real_escape_string function, which takes care of escaping the data for you.
    You could use that on the data in the previous examples like so:

    // Prepare all fields for being used in a MySQL query.
    $safeData = array();
    foreach($fields as $_field) {
        $safeData[$_field] = mysql_real_escape_string($_POST[$_field]);
    }
  2. Hash your passwords!
    A basic way to protect your user's passwords from being known by others, including you, is to use a one-way encryption algorithm on it, known as "hashing", to turn it into a long string of seemingly random characters.
    Then you store the hash in the database as the user's password. When it comes time to log the user in, you hash the password he provides in the same way you did when it was created, and compare the two. If the hashes match, it is valid.
    // Create a password hash. Never store passwords as plain text!
    $passwordHash = hash("sha256", $safeData['password']);
  3. And then you create and execute the query, using the now secure data.
    // Compile the query, using the verified data
    $sql = "SELECT `id` 
            FROM   `user` 
            WHERE   
                (`username` = '{$safeData['username']}')
            AND (`email` = '{$safeData['email']}')
            AND (`passwordHash` = '{$passwordHash}')";
  4. Which you would finish of like so:
    // Execut the query and check the results.
    $result = mysql_query($sql);
    if($result && mysql_num_rows($result) == 1)
    {
        echo "Login succesfull!";
        
        // And then do stuff to actually log him in.
    }
    else
    {
        echo "Login failed! Better luck next time.";
    }

I'll leave it there... for now :)

That was nice Atli... I need to learn how to create that custom regex codes. May be a link to some tutorial can be helpful..

Sure. Try this one. It's what I used when I was first starting out with regular expressions.
And you can check out the details on how PHP uses them here.

Regular expressions can be a bit tough to work with tho, even when you know all about them, and they are not the easiest thing to learn. It's worth it tho. They are an extremely powerful tool.

Sure. Try this one. It's what I used when I was first starting out with regular expressions.
And you can check out the details on how PHP uses them here.

Regular expressions can be a bit tough to work with tho, even when you know all about them, and they are not the easiest thing to learn. It's worth it tho. They are an extremely powerful tool.

Thanks for the prompt reply... lemme just start off with the link u provided n then will let u knw if i need som help...
actually i come across various regex in javascript snippets n found them pretty amazing n helpful.
Just wanted to learn to write them by myself... Thanx again...:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.