Jason
Jason

Reputation: 11363

Debugging PHP validation script

I'm building a micro-site, and am having trouble with the password reset behavior.

There is a form that asks the user for their password twice. I'm not being a password nazi, and the only requirement is that the password be greater than 5 characters. On submit, the form data is added to the $_POST array and is sent to a setPass function in my site-wide php function script.

The function is

function setPass(){
    $link= connectDB();

    $query= "select * from People where Username='" . $_SESSION['name'] . "' Limit 1";
    $result= $link->query($query);

    if ($result->num_rows==0){
        $_SESSION['status']= 'invaliduser';
        header("location: ../index.php");
    } else {
        $first = $_POST['firstPass'];
        $second = $_POST['secondPass'];

        if (($first == $second) && (strlen($first) > 5)){
            $password = sha1($first);
        }
    }
}

I'm leaving out the database insertion code in this example.

My issue is that this script echo $_SESSION['name'] . " and password: " . $first; included in the page body prints out the username, but returns an unidentified variable: first warning. This also happens when I try to access the variable $password.

Earlier testing has shown that the first conditional is true, as the page is not redirected.

So what is causing the failure of execution in the else block?

Upvotes: 2

Views: 101

Answers (3)

Anton
Anton

Reputation: 1515

It looks to me like a problem with scopes. You might want to try to use either session or more preferably global variables.

Check this out for more info: http://php.net/manual/en/language.variables.scope.php

[EDIT]

Or even better, return $first from the function like Borealid suggested.

Upvotes: 1

AlexC
AlexC

Reputation: 1141

You say that you're echoing in the body of the script? You defined the variable inside a function, so unless you set it as global(generally not a good idea, see PHP global in functions), $first really doesn't exist.

Upvotes: 2

Borealid
Borealid

Reputation: 98559

Since you set $first and $password inside the setPass function, they are not available outside the body of same.

You should use the global keyword or, possibly better, return the values from the function if you wish to use them outside.

This concept is called the scoping of variables. These variables have local scope within the function. See here for a comprehensive description of scoping in PHP.

Upvotes: 4

Related Questions