Tamim Addari
Tamim Addari

Reputation: 7831

Validating form using php session

I am trying to validate my form using php. Upon validation it will give a welcome message.Or else it will redirect to the index page. I have used session to save the variable. But the problem is nothing happen's when I submit the form, Here's my script

<?php session_start();
    $_SESSION['reg'] = array();
    $name = $_POST['name'];
    $email = $_POST['email'];
    $passwd = $_POST['passwd'];
    $repasswd = $_POST['repasswd'];

if(empty($_POST)){
    header("location:register.php");
}
else
{
    if(empty($name)){
        $_SESSION['reg']['name'] = "Please enter name";
    }
    if(empty($email)){
        $_SESSION['reg']['email'] = "Please enter email";
    }
    if (empty($passwd)) {
        $_SESSION['reg']['passwd'] = "please enter a password";
    }
    elseif (strlen(passwd)>16) {
        $_SESSION['reg']['passwd'] = "At most 16 chars";
    # code...
    }
    if ($passwd != $repasswd) {
        $_SESSION['reg']['repasswd'] = "Passwords don't match";
    }
    if (empty($_SESSION['reg'])) {
        header("location:welcome.php");
    }
    else
    {
        $_SESSION['data'] = array();
        foreach($_POST as $id=>$val)
        {
            $_SESSION['data'][$id] = $val;

        }
        header("location:register.php");
    }

?>      

when I submit the form, It shows a blank page.

Upvotes: 0

Views: 5845

Answers (1)

Revent
Revent

Reputation: 2109

The problem is that you are not storing your post variables into the session if they are NOT empty prior to checking

if (empty($_SESSION['reg'])) {

I would highly suggest doing some sql injection prevention prior to putting post variables into the session scope.

UPDATE: So if you want the variable in the session scope, instead of checking if(empty($name)){ and setting an error message in the session, I would do this:

if( !empty($name) ){
   $_SESSION['reg']['name'] = $name;
} else {
   // error handling
}

this will set the session variable if the posted value is NOT empty. Now when you check your session variable later on, it will have the name value in it and won't be empty.

Upvotes: 1

Related Questions