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:
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:
header('Location: index.php');
exit;
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.
Better way of doing things: Check for the session variable in the index.php and redirect if it is not set. Something like this
session_start();
if (!isset($_SESSION['auth']) || $_SESSION['auth'] != 1) {
header('Location: login.php');
exit();
}
echo 'Hello';
In the login.php, after successful authentication, redirect to index.php and do the echo there.
session_start();
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
$_SESSION['auth'] = 1;
setcookie("username", $_POST['name'], time()+(84600*30));
header('Location: index.php');
exit();
}
else {
echo "ERROR: Incorrect username or password!";
}
session_start() should come before any content is echoed to the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With