If statement acting very wierd, not recognizing simple input

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ninjapheret
Forum Newbie
Posts: 2
Joined: Thu Mar 16, 2006 8:02 pm

If statement acting very wierd, not recognizing simple input

Post by ninjapheret »

My script has a username/password combo stored in a file, file.pass, with the username on the first line and password on the second, so...

FILE.PASS:
----------------
bob
bobpass
----------------

$userpass = file("file.pass");

therefore

echo $userpass[0]; // this would return 'bob'
echo $userpass[1]; // this returns 'bobpass'

So then why doesn't a form, with two fields, where one = username and one = password not work in the following scenario:

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

if ($username == $userpass[0]) {
echo "success!";
} else {
echo "error!";
}

And I keep getting "error!" instead of "success!" -- why???
User avatar
a94060
Forum Regular
Posts: 543
Joined: Fri Feb 10, 2006 4:53 pm

Post by a94060 »

yo might keep on getting error because it does not match bob and bobpass. are you sure you are puting bob as user name and bobpass as password? also,those are the first values in the pass file right?
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Post by ambivalent »

Code: Select all

$userpass = file("file.pass");

var_dump($userpass);
Output:

Code: Select all

array(2) { [0]=>  string(4) "bob " [1]=>  string(7) "bobpass" }
Seems to be including whitespace after "bob". Try trim() on $userpass[0]
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

String are translated to integers for comparison. Could either type cast the variables (be sure to use ===) or use strcmp.
ninjapheret
Forum Newbie
Posts: 2
Joined: Thu Mar 16, 2006 8:02 pm

Post by ninjapheret »

Ah trim might just do it! Lemme try that in one second!

The reason I knew they were matching is that I did an else{} statement after the un/pw check that did the following:

echo $userpass[0];
echo $username;
echo $userpass[1];
echo $password;

and they matched up perfectly... but there might have been a rogue space now that i think about it... ill post back in a minute.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

My guess is that with file you also have the newline character at the end of a line in a file...

So, when you echo $file[0] you get to see "timvw" where the actual output is "timvw\n" or "timvw\r\n"...
Post Reply