index.php
<?php
if( $_SESSION['auth'] != 1 ) {
require( 'login.php' );
}
else {
echo "hello";
}
?>
login.php
<?php
$name = $_POST['name'];
$pass = $_POST['pass'];
if( isset($name) || isset($pass) )
{
if( empty($name) ) {
die ("ERROR: Please enter username!");
}
if( empty($pass) ) {
die ("ERROR: Please enter password!");
}
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
session_start();
$_SESSION['auth'] = 1;
setcookie("username", $_POST['name'], time()+(84600*30));
echo "Access granted!";
}
else {
echo "ERROR: Incorrect username or password!";
}
}
// If no submission, display login form
else {
?>
<html>
<head></head>
<body>
<center>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" name="name" value="<?php echo $_COOKIE['username']; ?>">
<p />
Password: <input type="password" name="pass">
<p />
<input type="submit" name="submit" value="Log In">
</center>
</body>
</html>
<?php
}
?>
So, as I’m still learning PHP, there’s a few things I’m trying to figure out now:
- How do I get it so I can reload index.php and it displays ‘hello’?
- How can I get login.php to auto-load index.php on a successful authentication so I can get it to that “hello”?
- Later, would using a cookie to store the user’s submitted login data (so they don’t have to refill the form to restore their session) have any potential problems?
Help appreciated.
1, You’re missing session_start() in index.php. Add it and you should be able to see ‘Hello world’
2, Replace your line with “Access granted!” with a redirect:
3, You can definitely store credentials in a cookie, but you should always hash and salt the password. Here is a good article about password hashing.