Question

I am currently writing a php script that validates a username and password. I am working by testing things little by little and right now I have a password file with only one line in it:

user:0011

I am using preg_split to parse the lines in this file and have the following code in my php script:

<html>
<body>

<?php 

    ini_set('display_errors',1);
    error_reporting(E_ALL);

    $usr = $_POST['username'];
    $pass = $_POST["pword"];


    $f = fopen('passwords.txt','r');
    $auth = false;

    while(!feof($f))
    {
        $login = preg_split("/:/",fgets($f));
        echo $login[0]."<br/>";
        echo $login[1]."<br/>";
        print_r($login);
        if($usr == $login[0] && $pass == $login[1])
        {
            echo "in if<br/>";
            $auth = true;
            break;
        }
    }

    if($auth)
        echo "success";
    else
        echo "fail!";

    /*$test = preg_split("/:/","me:you");
    echo $test[0];*/


    fclose($f);
?>

</body>
</html>

The problem is that this is the output it give me is:

user
0011
Array ( [0] => user [1] => 0011 )
Notice: Undefined offset: 1 in /srv/www/htdocs/PHP/val.php on line 20
Array ( [0] => ) fail!

This error doesn't make sense to me because it is implying that the array is not long enough to have a value at index 1, but I just printed that value and even in the result from print_r it shows there being a value at that index. Does anyone have any idea what is causing this error?

Was it helpful?

Solution

You're on the second iteration of the while loop is my guess; try throwing in a simple counter to check. If you have a newline in the file that would do it.

try doing this at the top:

$lrec = trim(fgets($f));
if (empty($lrec)) {
    continue;
}
$login = preg_split("/:/",$lrec);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top