Home > Enterprise >  Something wrong when getting data from text
Something wrong when getting data from text

Time:06-24

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.

CodePudding user response:

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.

CodePudding user response:

$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";
    }
}
?>

CodePudding user response:

Storing login information like this is horribly insecure. However, if you are learning, then there is an easier way to do this.

Instead of looping through the contents, just look for the username|password combination.

$f = file_get_contents ("users.txt") . "\r\n";
$login = $_POST["login"] . " | " . $_POST["password"] . "\r\n";
if(strpos($f,$login) !== false){
   echo "Works!";
}
  •  Tags:  
  • php
  • Related