I\'m currently working on a site that has a log-in (username and password) - The password protection is done by the operating system within the web server at folder level ca
The folder being password protected has nothing to do with PHP!
The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...
Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess
or wherever it is first):
login.php:
<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
$_SESSION['logged_in'] = true;
header('Location: /index.php');
}
else
{
?>
<form method="POST">
Username: <input name="user" type="text"><br>
Password: <input name="pass" type="text"><br><br>
<input type="submit" value="submit">
</form>
<?php
}
index.php
<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
?>
<p>here is my super-secret content</p>
<a href='logout.php'>Click here to log out</a>
<?php
}
else
{
echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}
logout.php:
<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';
Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.
Hope this helps you understand what's going on.
First give the link of logout.php
page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
// logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
?>