-1

I'm practicing some php and I am creating this password system. my code doesn't work. anyone notices a mistake? I think it's just a stupid fault, but i can't seem to find it.

<?php
$passwords = array("name1"   =>"pass1", 
                   "name2"   =>"pass2");

if ($password = $passwords[$username]){
setcookie("username", $username, time()+1200);
echo "<H2>Access granted.</H2>";
}
else{
    setcookie("username", "", time()-3600);
    echo "<H2>Invalid user name or password: access denied.</H2>";
}
?>

thanks everyone! my stupid fault was that i used = instead of == to check if $password is equal to $passwords[$username]

Goos van den Bekerom
  • 1,475
  • 3
  • 20
  • 32

6 Answers6

3
<?php
$passwords = array("name1"   =>"pass1","name2"   =>"pass2");
if ($password == $passwords[$username]){
 setcookie("username", $username, time()+1200);
 echo "<H2>Access granted.</H2>";
}
else{
    setcookie("username", "", time()-3600);
    echo "<H2>Invalid user name or password: access denied.</H2>";
}
?>

You have forgot = in this row:

  if ($password == $passwords[$username]){

If you use this '=' you define this variable. But '==' it checks the variable!

Rajeev Ranjan
  • 4,152
  • 3
  • 28
  • 41
STP38
  • 348
  • 2
  • 14
2

You are doing an assignment instead of comparison on your if statement.

Should be like

if ($password == $passwords[$username]){

Note the == instead of =

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

Use Double equal for the comparision.If you give single equal the it will only assign the right side variable to left side variable,and that to,the assigning will return always true

if ($password == $passwords[$username]){
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

Use if like this:

if ($password == $passwords[$username]){
//code
}
Sherin Jose
  • 2,508
  • 3
  • 18
  • 39
0

You are using assignment operator(=) instead of equality operator(==). Replace with

if ($password == $passwords[$username])
Jenz
  • 8,280
  • 7
  • 44
  • 77
0

Like this

if ($password == $passwords[$username])

Use == instead of = in if statement.

Pratik
  • 810
  • 6
  • 26