0

I am a login/register page and I have this for my login:

session_start();

$username = $_POST["username"];
$password = $_POST["password"];

$user_infile = "";
$password_infile = "";

$user_data = fopen("user_data.txt", "r");

while(! feof($user_data)){
    $userArray = fgetcsv($user_data);

    if ($userArray[0] == $username){
        $user_infile = $userArray[0];
        $password_infile = $userArray[1];
    }
    
}

if (strval($password)  ==  strval($password_infile)){
    $_SESSION["loggedin"] = true;
    $_SESSION["username"] = $username;
    $_SESSION["password"] = $password;
    header('Location: home.php');
    exit();
}
else{
    header('Location: error.php');  
    exit();
}

The login works perfect if the password is numeric i.e 123, but if password contains characters ie abc, the comparison fails and the else statement is executed. I used strval to convert both to string, but didnt work. I simply used password == password, that didnt work too. strcmp also didnt work. Am I missing something here?

Edit: This is the input file:

new, 123, 0
admin, pass, 0
jon, a1, 0
10
  • As everything that come to you via $_POST is a string, why are you using strval() Commented Nov 5, 2020 at 15:38
  • 2
    Side note: use a break; after you find the user to avoid iterate through all the file after you find the user Commented Nov 5, 2020 at 15:39
  • It may be useful to see what the input file looks like Commented Nov 5, 2020 at 15:40
  • 2
    var_dump($password, $password_infile); to see what's different. Commented Nov 5, 2020 at 15:42
  • 3
    @Efaz probably you need to trim($password_infile); Commented Nov 5, 2020 at 15:43

1 Answer 1

1

You should add quotes around your text field to be sure that fgetcsv reads it all, then modify the fgetcsv to include the character used as a text delimiter. In general CSV files should not contain extra spaces around the delimiter as these can be interpreted as being part of a field. Make sure you remove all spaces that are not part of the fields. You should also remove the strval calls and simply compare the two values.

"new","123",0
"admin","pass",0
"jon","a1",0

$userArray = fgetcsv($user_data, 0, ',', '"');

if ($password == $password_infile) { // etc.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.