Php Tutorial 3 – Form Validation in PHP

Welcome to tutorial 3, where we will learn to validate a form’s data through PHP.

Forms are a crucial part of a webpage without which, no significant input from the user can be expected. Before submitting a form’s data to the back-end, it needs to be validated due to certain issues. Form validation through PHP is a process where the form data is posted to the server and server returns the respective messages related to the validation.Validation of a form’s data is generally practiced with the aid of JAVASCRIPT because the form’s data is validated by the browser only, showing respective messages without returning to the server. Here, we will stick to the form validation process through PHP only.

So the webpage containing the form, index.php, will go like:

<?php include("form.php"); ?>
<html>
    <head>
        <title>PHP Tutorial 3 - Form Validation Demo</title>
    </head>

    <body>
        <?php
        /* Form submitted without errors */
        if(isset($_SESSION['submit']))
        {
            if($_SESSION['submit'])
            {
            ?>
                <h1>Form Submitted!</h1>
            <?php
            }
            unset($_SESSION['submit']);
        }
        else // error in the form or first load of the page
        {
        ?>
            <h1>Login</h1>
            <?php
            /* If errors occurred, they will be displayed. */
            if($form->num_errors > 0)
                echo "<font size="2" color="#ff0000">".$form->num_errors." error(s) found</font>";
            ?>
            <form action="process.php" method="POST">
                <table>
                    <tr>
                        <td>Username: </td>
                        <td><input type="text" name="user" maxlength="30" value="<?php echo $form->value("user"); ?>"></td>
                        <td><?php echo $form->error("user"); ?></td>
                    </tr>
                    <tr>
                        <td>Password: </td>
                        <td><input type="password" name="pass" maxlength="30" value="<?php echo $form->value("pass"); ?>"></td>
                        <td><?php echo $form->error("pass"); ?></td>
                    </tr>
                </table>
                <p>
                    <input type="hidden" name="sublogin" value="1">
                    <input type="submit" value="Login">
                </p>
            </form>
        <?php
        }
        ?>
    </body>
</html>

in the above codes, under the form section, each field is followed by error message of the corresponding field. At the first load of the page, all the messages are blank therefore no message can be seen. But once a form is submitted to the page process.php, the data corresponding to every field is validated and the error messages for the corresponding fields are altered. After the validation of entire data, the server is again redirected to the page index.php. At this load of the page, the corresponding ‘new’ error messages are visible along with the count of the number of errors.

The contents of process.php goes like this:

 <?php
include("form.php");
class Process
{
    function Process()
    {
        /* User submitted login form */
        if(isset($_POST['sublogin']))
        {
            $this->procLogin();
        }
        else
        {
            header("Location: index.php");
        }
    }

    function procLogin()
    {
        global $form;
        /* Username error checking */
        $subuser = $_POST['user'];
        $subpass = $_POST['pass'];
        $field = "user";  //Use field name for username
        if(!$subuser || strlen($subuser = trim($subuser)) == 0)
        {
            $form->setError($field, "* Username not entered");
        }
        $field = "pass";  //Use field name for username
        if(!$subpass || strlen($subpass = trim($subpass)) == 0)
        {
            $form->setError($field, "* Password not entered");
        }
        /* Errors exist, have user correct them */
        if($form->num_errors > 0)
        {
            $_SESSION['value_array'] = $_POST;
            $_SESSION['error_array'] = $form->getErrorArray();
        }
        else
            $_SESSION['submit'] = true; // No errors, form can be submitted now

        header("Location: index.php");
    }
};

/* Initialize process */
$process = new Process;

?>

A file form.php is included in both the pages above. It includes various functions that are called by both the pages. Let us consider the following segment from process.php :

$subuser = $_POST['user'];
$field = "user";  //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0)
{
    $form->setError($field, "* Username not entered");
}

The ‘if’ condition validates whether the data posted under ‘user’ field is null or not. If the condition proves to be valid, the error message for the ‘user’ field is set to be ‘*Username not entered’. This is carried out by calling the function ‘$form->setError($field, “* Username not entered”);’ from the page form.php. Here ‘$field’ contains the name of the field, the data of which is being validated, followed by the message which needs to be set for the current field.

The contents of form.php goes like:

<?php
class Form
{
    var $values = array();    //Holds submitted form field values
    var $errors = array();  //Holds submitted form error messages
    var $num_errors;   //The number of errors in submitted form

    function Form()
    {
        session_start();
        /**
        * Get form value and error arrays, used when there
        * is an error with a user-submitted form.
        */
        if(isset($_SESSION['value_array']) && isset($_SESSION['error_array']))
        {
            $this->values = $_SESSION['value_array'];
            $this->errors = $_SESSION['error_array'];
            $this->num_errors = count($this->errors);

            unset($_SESSION['value_array']);
            unset($_SESSION['error_array']);
        }
        else
        {
            $this->num_errors = 0;
        }
    }

    /**
    * setError - Records new form error given the form
    * field name and the error message attached to it.
    */
    function setError($field, $errmsg)
    {
        $this->errors[$field] = $errmsg;
        $this->num_errors = count($this->errors);
    }

    /**
    * value - Returns the value attached to the given
    * field, if none exists, the empty string is returned.
    */
    function value($field)
    {
        if(array_key_exists($field,$this->values))
        {
            return htmlspecialchars(stripslashes($this->values[$field]));
        }
        else
        {
            return "";
        }
    }

    /**
    * error - Returns the error message attached to the
    * given field, if none exists, the empty string is returned.
    */
    function error($field)
    {
        if(array_key_exists($field,$this->errors))
        {
            return "<font size="2" color="#ff0000">".$this->errors[$field]."</font>";
        }
        else
        {
            return "";
        }
    }

    /* getErrorArray - Returns the array of error messages */
    function getErrorArray()
    {
        return $this->errors;
    }
};

/* Initialize form */
$form = new Form;

?>

A combination of these three pages: index.php, process.php, form.php will help you out in validating a forms data through PHP. Click here to download a working script.

Keep looking for more posts regarding PHP.

Php Tutorial 2 – Hello World Program

Welcome back to the tutorial 2, here we will start our programming in php. We will make different folders for different tutorials, so first make a Tutorial 2 folder in www directory. We will do our programming in notepad or for your use you may use different user friendly text editors like notepad ++. Php files have .php extension, index.php is the file which is automatically executed in a folder, so make a index.php in Tutorial 2 folder and type the below code in .

In a php file we can add HTML, CSS, JAVASCRIPT or anyother language so we have php tags which tell the server that the lines inside these tags are php codes, opening tag for php is <?php and closing tag is ?>

e.g.

<?php

……

code

……

?>

now lets code for a simple hello world program.

<html>

<head>

<title>Innovation Escalator Tutorial</title>

</head>

<body>

<?php

echo “Hello World”;

?>

</body>

</html>

echo command is used for printing, and each and every statement is terminated by a use of a semicolon.

Use of variables, loop and if conditions in php:

<?php

for($i=0;$i<10;$i++)

{

if($i%2 == 0)

echo “Hello<br>”;

}

?>

the above php code prints hello only when the value of variable i is even. In php we just use a $ sign before a variable moreover we don’t need to define the variable type its up to you what data type you want to store, its a kind of flexibility.

This is all about basic of php… wait for next. Till then if you have any queries you make post them.

 

Php Tutorial 1 – Setting up localhost

Hi everyone I’m starting with the tutorials of php here in a series, hope it help you guys, stay updates for a series of php tutorials.

As you know php is a server side scripting language, it is mainly used to develop websites and web-applications. Since it is a server side scripting language you need a server to run your php files, for this there are two options i.e either you get your web hosting account or setup your own server. I find setting up your server is a better option so here I will  tell you how to install it, I use WAMP server which automatically configures php, mysql, apache and phpmyadmin. Just click on the link below to download wamp server:

http://www.wampserver.com/en/download.php

download 32bit version or 64bit according to your requirement.

After installing you will get a shortcut on your desktop, start it by double clicking it you will get a wamp icon in your taskbar.

Click on that icon to get menu…

Wamp menu

>localhost – it will open the address of localhost in your web browser.

>phpmyadmin – this is a installed alias which will help you manage your databases.

>www directory – this is the directory where you will place you php files/projects to run.

>apache – manages apache extensions.

>php – manages php extensions.

>mysql – manages mysql extensions.

 

That was all about installing wamp server i.e setting up a localhost.

Next post will we a very simple post just telling you about a hello world program in php… till then install php… :)