Ahmadali Shafiee
Ahmadali Shafiee

Reputation: 4657

why if statement doesn't work?

I have this php code:

$flag = 0;
$f = fopen("1.txt", "r");
while (!feof($f))
{
    $a = fgets($f);
    $b = explode(",", $a);
    if ($_POST['username'] == $b[0]&& $_POST['password'] == $b[1])
    {
        $flag = 1;
        echo ("Correct");
        break;
    }
}
 if ($flag == 0)
     echo ("Incorrect");
fclose($f);

and 1.txt file is this:

1,1
2,2
3,3
4,4
5,5

I send data to my php page that have just this code but I always get Incorrect. I don't know why if doesn't work!(I checked the $_POST['username'] and $_POST['password'] but all were correct!) can anybody help me?

Upvotes: 0

Views: 220

Answers (5)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Heres how I would do it, using file()

<?php 
//Get file
$file = file('1.txt');

//Split the array line in two with delimiter ,
function split_it(&$value){
        $value = explode(',',$value);
}
array_walk($file,'split_it');

//Check values passed against the array, and return true or false
function check_it($file,$a,$b){
    foreach($file as $row){
        if(trim($row[0])==trim($a) && trim($row[1])==trim($b)){
            return true;
        }
    }
    return false;
}


//The business part
$a = (isset($_POST['a'])?$_POST['a']:null);
$b = (isset($_POST['b'])?$_POST['b']:null);

if(check_it($file,$a,$b)==true){
    echo 'Correct';
}else{
    echo 'In-correct';
}
?>

Upvotes: 1

Justin Warkentin
Justin Warkentin

Reputation: 10241

You may need to trim($b[1]) because it probably reads the new line into the string so $b[1] would never be equal.

Edit:

Actually, you should just replace $a = fgets($f); with $a = trim(fgets($f));

Upvotes: 3

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

It works:

$flag = 0;
$f = fopen("1.txt", "r");
while (!feof($f))
{
    $a = fgets($f);
    $a = trim($a);
    $b = explode(",", $a);
    var_dump($b);
    if ($_POST['username'] == $b[0] && $_POST['password'] == $b[1])
    {
        $flag = 1;
        echo ("Correct");
        break;
    }
}
if ($flag == 0)
    echo ("Incorrect");
fclose($f);

Upvotes: 1

Woody
Woody

Reputation: 363

Simple echo b[0], b[1], $_POST['username'], and $_POST['password']

I have a feeling one of these values won't be what you expect, which will help you solve your problem.

Upvotes: 1

Michael Roewin Tan
Michael Roewin Tan

Reputation: 454

Separate $b[0] from && to make if statement work.

 if ($_POST['username'] == $b[0] && $_POST['password'] == $b[1])
    {
        $flag = 1;
        echo ("Correct");
        break;
    }

Upvotes: -1

Related Questions