Domanda

I wanted to build a super-simple login-script with a text-file. Text-file contains

password    username    name

Between the password, username and name is a tab. I read the file, explode it by tab, and then check the user input against the lines.

But I always get (one) Undefined offset error. I think it is because of the explode function, but I don't know why...

Here's my code:

if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
{
    $log = 0; //not logged in
    $username = $_POST['login_inputEmail'];
    $password = $_POST['login_inputPassword'];
    $userdatei = fopen ("documents/user.txt","r");
    while (!feof($userdatei))
       {
       $zeile = fgets($userdatei,800);
       $userdata = explode("\t", $zeile);
       if ($username == $userdata[1] && $password == trim($userdata[0]))
          {
          $log = 1; //logged in
          }
       }
    fclose($userdatei);
}
È stato utile?

Soluzione

Add is_array() and isset() in your code to avoid errors. Refer this

 if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
 {
     $log = 0; //not logged in
     $username = $_POST['login_inputEmail'];
     $password = $_POST['login_inputPassword'];
     $userdatei = fopen ("documents/user.txt","r");
     while (!feof($userdatei))
     {
        $zeile = fgets($userdatei,800);
        $userdata = explode("\t", $zeile);
        if(is_array($userdata))
        {
           if(isset($userdata[1]) && isset($userdata[0]))
           {
              if ($username == $userdata[1] && $password == trim($userdata[0]))
              {
                 $log = 1; //logged in
              }
           }
        }
     }
    fclose($userdatei);
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top