Pergunta

This is a script using cookies for password.....running it on localhost it show the notice undefined index:user undefined index:pass
The code is as follows:

<html>
<body>
<form action="<?php echo ($self); ?>" method="post">
Please enter your details for access :<br>
Name:<input type="text" name="user" size="10">
Password:<input type="text" name="pass" size="10"><br><br>
<input type="submit" value="Log in">
</form>
</body>
</html>
<?php
$user=$_POST['user'];
$pass=$_POST['pass'];
$self=$_SERVER['PHP_SELF'];
if(($user!=null)and ($pass!=null))
{
 if($pass=="mypassword")
  {
    setcookie("checkpass","okkay");
header("Location:loggedin.php");
exit();
  }
 else
  {
  setcookie("checkpass");
 } 
}
?>
Foi útil?

Solução

This is happening because you need to use isset and wrapping that conditional statement around your PHP.

Plus, you will get an error message such as:

Warning: Cannot modify header information - headers already sent by (output started at.....

So, place your PHP above HTML.

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

if(isset($_POST['user']) && isset($_POST['pass'])){

$user=$_POST['user'];
$pass=$_POST['pass'];
$self=$_SERVER['PHP_SELF'];
if(($user!=null) and ($pass!=null))
{
 if($pass=="mypassword")
  {
    setcookie("checkpass","okkay");

// echo "OK";

 header("Location:loggedin.php");
exit();
  }
 else
  {
  setcookie("checkpass");

// echo "SORRY";

 } 
}

} // brace for if(isset($_POST['user']) ...
?>

<html>
<body>
<form action="<?php echo ($self); ?>" method="post">
Please enter your details for access :<br>
Name:<input type="text" name="user" size="10">
Password:<input type="text" name="pass" size="10"><br><br>
<input type="submit" value="Log in">
</form>
</body>
</html>

Passwords

I also noticed that you may be storing passwords in plain text. This is not recommended.

Use one of the following:

Other links:

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top