<?php
session_start();
// declare variables //
$username = 'username';
$password = 'password';
$random1 = 'secret_key1';
$random2 = 'secret_key2';
$hash = md5($random1.$pass.$random2);
$self = $_SERVER['REQUEST_URI'];
// user logout //
if(isset($_GET['logout']))
{
unset($_SESSION['login']);
}
// user is logged in //
if (isset($_SESSION['login']) && $_SESSION['login'] == $hash) {
?>
<p>Hello <?php echo $username; ?>, you have successfully logged in!</p>
<a href="?logout=true">Logout?</a>
<?php
}
// form has been submitted //
else if (isset($_POST['submit'])) {
if ($_POST['username'] == $username && $_POST['password'] == $password){
// username and password are correct
$_SESSION["login"] = $hash;
header("Location: $_SERVER[PHP_SELF]");
} else {
// display form with errors
display_login_form();
echo '<p>Username or password is invalid</p>';
}
}
// show the login form //
else {
display_login_form();
}
function display_login_form(){ ?>
<form action="<?php echo $self; ?>" method='post'>
<label for="username">username</label>
<input type="text" name="username" id="username">
<label for="password">password</label>
<input type="password" name="password" id="password">
<input type="submit" name="submit" value="submit">
</form>
<?php } ?>
A simple login based on PHP with no database.
3 Responses
Thanks for this script, really helpful. Can I ask you, how to logout again?
Cheers from Zurich
Luca
session_destroy();
Write a comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.