Val
Val

Reputation: 23

Something wrong when getting data from text

I have a code in index.php:

<input type="text" name="login">
<input type="text" name="password">
<input type="submit" name="submitBtn"> 

then

<?php
$f = file_get_contents ("users.txt");
$data = explode("\n", $f);
$k = count($data);

for ($i=0; $i<$k; ++$i) {
    $user_array[$i] = explode (" | ", $data[$i]);
}
            
if (isset($_POST["submitBtn"])) {
    if ($_POST["password"] == $user_array[$i][1]) {
        echo "works";
    }
}
?>

This code should say "works" when password in POST matches with password in txt-file. But it does not. If I match login with $user_array[$i][0] it works.

login and passwords are in txt-file saved like this:

login1 | pass1
login2 | pass2

And so on

Types are the same string, I checked it. It should be something I do not see.

Upvotes: 0

Views: 78

Answers (2)

RobIII
RobIII

Reputation: 8821

Your code can be written much more efficiently:

<?php
if (isset($_POST["submitBtn"])) {
  $login = $_POST["login"];
  $password = $_POST["password"];

  foreach (file("users.txt") as $line) {
    list($user, $pass) = explode(' | ', $line);
    if ($login === $user && $password === $pass) {
      echo 'Works';
      break;
    }
  }
}

Or, create a 'lookup' array (hashmap, dictionary, whatever you wanna call it):

<?php
if (isset($_POST["submitBtn"])) {
  foreach (file("users.txt") as $line) {
    list($user, $pass) = explode(' | ', $line);
    $logins[$user] = $pass;
  }

  $login = $_POST["login"];
  if (isset($logins[$login]) && $logins[$login] === $_POST["password"])
    echo 'Works';
}

Other than that, this is just for demonstration purposes only!

DO NOT USE THIS IN ANYTHING CONNECTED TO THE INTERNET - IT IS HORRIBLY INSECURE!

I've tried to not overcomplicate the examples and keeping it readable at the same time; there's lots more things you can do.

Upvotes: 1

Milad Elyasi
Milad Elyasi

Reputation: 960

$i is only in your loop. it's your iterator variable.

you may change your code like this:

<?php
$f = file_get_contents ("users.txt");
$data = explode("\n", $f);
$login=[];
foreach($data as $item){    
     /*
      *   [ "login1" => "pass1" , "login2" => "pass2" ]
      */
    $array = explode (" | ", $item);
    $login[$array[0]] = $array[1];
}
            
if (isset($_POST["submitBtn"])) {
    // check if password is in array values!
    if (in_array($_POST["password"],$login)) {
        echo "works";
    }
}
?>

Upvotes: 0

Related Questions