Question

So right now I'm making a simplistic login system. The client enters the form data and the php handles it by checking a text file that goes like so:

name
pass
name
pass
...so on

The php I'm using to process this is:

$name = $_REQUEST['name'];
$pass = $_REQUEST['pass'];
$validName = false;
$validPass = false;
$pos = 0;

$file_handle = fopen("database.txt", "r");

while (!feof($file_handle)) {

    $line = ltrim( fgets($file_handle), "\n" );

    if ($pos % 2 == 0 ) // Checks for names first on even rows
    {
        if( strcmp( $name, $line))// Normal checking returns correctly
            $validName = true;
    }
    else if( $validName === true ) // if odd, and a matching name check pass
    {
        if( !strcmp( $pass, $line) )// What's going on here? Why is it opposite?
        {
            $validPass = true;
        }
        break;
    }
    $pos++;
}

What's happening is that the first check if( strcmp( $name, $line)) checking if there is a name in the data base that matches the input from the client.

This correctly returns true when the clients name matches a name in the data base. I check the password the EXACT same way, but some how it returns false when it's suppose to be true, and returns true when it's suppose to be false.

What's going on here?

On a side note, I'm only using strcmp because I couldn't get $name === $line to work.

Was it helpful?

Solution

strcmp() returns an integer, not a boolean. In fact, it returns 0 if the strings match, which would evaluate to false in an if-statement. That is why it appears to have "reverse" behavior compared to a typical boolean function.

See the documentation.

OTHER TIPS

According to your code, it is not exact same way, but rather opposite:

    if( strcmp( $name, $line))
    if( !strcmp( $pass, $line))

Looks like there was a bigger problem then I thought.

There was 2 problems.

1, As Daniel explained perfectly

2, There was an extra character at the end of each line which threw off all comparisons. So to fix this I deleted the end of the line and now everything's working.

while ( !feof($file_handle) ) 
{

    $line = ltrim( fgets($file_handle) );
    $line = substr($line, 0, -1);/// This gets rid of the extra character

    if ( ($pos % 2) == 0 )
        $validName = ( $name === $line );// compares with ===, which is faster then strcmp
    else if( $validName )
    {
        $validPass = ( $pass === $line );
        break;
    }

    $pos++;
}fclose($file_handle);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top