My problem may seem pretty elementary, but I dont know whats wrong with my code. I have a very simple login system that looks like this:
login.php:
<?php
session_start();
if ($_SESSION['loggedin'] = 1) {
header("Location: admin.php");
}
if ($_GET['login']) {
// Only load the code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['username'] == 'thenemis'
&& $_POST['password'] == 'slustice') {
// Load code below if both username
// and password submitted are correct
$_SESSION['loggedin'] = 1;
// Set session variable
header("Location: admin.php");
exit;
// Redirect to a protected page
} else echo "Wrong details";
// Otherwise, echo the error message
}
?>
<form action="?login=1" method="post" accept-charset="utf-8">
<fieldset>
<label for="username">Usermame:</label>
<input type="text" name="username" placeholder="username" required>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="password" required>
<input type="submit" value="Login"> </td>
</fieldset>
</form>
This works fine.
admin.php:
<?php
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['loggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: login.php");
exit;
}
?>
<p>Log out</p>
Now my problem is, that the system keeps me logged even though i clicked the logout URL, which looks like this:
logout.php:
<?php
session_start();
session_destroy();
header("Location: login.php");
?>
There is obviously some elementary mistake with my logout procedure, but I cant seem to find it... Thanks for any help in advance!
You are making assignment here:
if ($_SESSION['loggedin'] = 1) {
header("Location: admin.php");
}
and you should make comparisment
if ($_SESSION['loggedin'] == 1) {
header("Location: admin.php");
}
Try this
<?php
session_destroy();
header('Location: index.php');
exit();
?>
change your admin.php file
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
}
?>
<p>Log out</p>
In login.php you didn't started session_start after user details verified...
try to add session_start(); before $_SESSION['loggedin'] = 1;
This may work for you...
in logout.php
before estroying unset the session variable
using this line
unset($_SESSION['loggedin']);
From the php.net Manual:
In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
Use this code (copied from php.net) to logout securely:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
Just try with the following changes :
In login.php :
if ($_SESSION['loggedin'] == 1) {
header("Location: admin.php");
}
In logout.php :
<?php
session_start();
ob_start();
session_destroy();
$_SESSION['loggedin']=""; //Just empty that session variable
header("Location: login.php");
?>
I think this may help you to resolve your problem.
Related
Whenever I run the logout.php script then go back to a page that is protected without login it will have me still logged in
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
exit();
?>
login.php
$userlogin = user_login($email, $password.$salt);
if ($userlogin==false){
$errors[]='Wrong email/password combination.';
} else {
//set the user session
$_SESSION['UserId']=$userlogin;
$_SESSION['LoginIP']=$_SERVER['REMOTE_ADDR'];
$db->query("UPDATE users SET ipadd='".$_SERVER['REMOTE_ADDR']."' WHERE user_id=".$_SESSION['UserId']."");
echo '<meta http-equiv="refresh" content="0; URL=index.php">';
Check logged in snippet
/* Check if user is logged in or not */
function loggedin(){
return (isset($_SESSION['UserId'])) ? true : false;
}
if (loggedin()==true){
$session_user_id = $_SESSION['UserId'];
$user_data = user_data($session_user_id,'full_name','username');
$rezult =$db->query("SELECT ipadd FROM users WHERE user_id=".$_SESSION['UserId']."");
while($rez = $rezult->fetch_assoc()){
if ($rez['ipadd']==$_SERVER['REMOTE_ADDR']) {
} else {
echo '<meta http-equiv="refresh" content="0; URL=logout2.php">';
}
}
}
Been look at posts with the same question but whatever I try still getting the same issue. Any advice would be extremely appreciated!
this is from php.net http://php.net/manual/en/function.session-destroy.php
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
so you just need $_SESSION = null, and logout should happen.
I think in your index.php file should have these line:
if(!isset($_SESSION["session_name"])){
header("Location: somewhere_mainpage.php");
}
It is better to make all pages have these line. These line will send header to another page if no session has started.
I believe that session_start(); function call should be on your login page when the user login data is correct, and in your logout PHP code, you should set
session_destroy(); or unset($_SESSION['UserId'];
Logout.php:
<?php
session_destroy();
/* * OR * */
//unset($_SESSION['UserId'];
header("Location: ../index.php");
exit();
?>
<?php
session_unset();
session_destroy();
header("Location: ../index.php");
?>
should work, otherwise you could unset the values
<?php
unset($_SESSION['UserId']); // Unsets the UserId Variable reuse for each variable
session_destroy();
header("Location: ../index.php");
?>
have you tried just session_destroy() ?
also I'm not sure wether you need session_start() when you are closing the session, from memory you only need it to start the session
I always like to destroy the server session, and client cookie, try to manually cover all options in case of any errors.
You can destroy the cookie in PHP with:
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly );
<?php
$cookie_path = "...";
$cookie_domain = "...";
$cookie_secure = "...";
$cookie_httponly = "...";
session_start();
session_unset();
session_destroy();
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain,$cookie_secure, $cookie_httponly );
header("Location: ../index.php");
exit();
time() - 3600 makes the cookie expiry before the current time, which makes it invalid.
Another option to investigate is session_regenerate_id() on your logout pages. Some reference pages are below:
php.net - session-regenerate-id
https://stackoverflow.com/a/22965580/1246494
I have made a login and register system, which works flawlessly, and I am very proud of, but I cannot seem to get a logout function working.
My login system basically takes the database and scans it for rows that have both the username and password specified, and if it does, then it makes $_SESSION['loggedin']=1; and if it fails it makes it equal to 0.
Once the user is done, he/she clicks on a link that redirects to logout.php, and that is where the issues start. I have put session_start(); at the beginning of each page, but session_destroy, session_unset, and combinations of the two cannot seem to kill the session.
So I am wondering, is there a way that upon loading logout.php, it sets the $_SESSION['loggedin] to 0, and then redirects back to index.php(my homepage)? Which means it doesnt kill the session, but it would effectively log the user out. Any help is appreciated.
// Four steps to closing a session // (i.e. logging out)
// 1. Find the session
session_start();
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
if session_destroy doesn't work, use instead:
unset($_SESSION['put your session in here']);
// logout.php
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1) {
$_SESSION['loggedin'] = 0;
header('Location: index.php');
}
It redirects the user to to index.php, if $_SESSION['loggedin'] equals to 1, and sets $_SESSION['loggedin'] to 0.
I suggest you to have 3 files
1) login.php
session_start();
/*if user $_POST username and password is correct then*/
$_SESSION['loggedin'] = 1;
?>
2)logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
$_SESSION['loggedin'] = 0;
?>
3)checkLogin.php
<?php
session_start();
if ( isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 0 )
{
echo "<script type='text/javascript'>alert('You need to login !')</script>";
echo '<meta http-equiv="Refresh" content="0;URL=index.php" />';
flush();
exit();
}
?>
with 3 files if you want to control some page that require login before access you just include(checkLogin.php);
e.g. index.php is not require login then not include(checkLogin.php);
but memberProfile.php is require login before then include(checkLogin.php);
I'm using the following code. Session is working on the same page; on the next page it is not showing the session variable value. Please let me know what I'm doing wrong?
<?php
session_start();
$_SESSION['emailaddress']=$emailAddress;
header("Location: $success "); /* Redirect browser */
exit;
?>
use session_start() in the page that you are redirecting to, as well ($success), before accessing the session values there
So that the "success.php" page looks something like:
<?
session_start();
print_r($_SESSION);
?>
<?php
if(some_condition is true)
{
session_regenerate_id();
session_start();
$_SESSION['emailaddress']=$emailAddress;
header("location: member-index.php");
exit();
}
on secure page:
<?php
//Start session
session_start();
//Check whether the session variable is present or not
if(!$_SESSION['emailAddress'])
{
header("location: access-denied.php");
exit();
}
?>
<p>This is secured page with session: <b><?php echo $_SESSION['emailAddress']; ?></b>
How do I destroy a session in php?
the thing is when the user clicks the logout button the session will end and he will be redirected to the index.php here's my code
Customer.php
<?php
session_start();
#include("Connection.php");
if (isset($_POST['submit'])) {
$name = $_POST['customerName'];
$_SESSION['user'] = $name;
}
if (isset($_SESSION['user'])) { echo "Hello {$_SESSION['user']}, welcome back"; }
else{echo "walang tao";}
$sql="INSERT INTO ORDERS(Name) VALUES('$name')";
mysql_query($sql);
session_destroy();
?>
<button></button>
and this is from the index.php where the user wants to log in again
<?PHP
/* this must go before any html */
session_start();
if (isset($_SESSION['user'])) {
header("location: Customer.php");
}
?>
<div class="sign">
<h2>Welcome</h2>
<form action = "Customer.php" method = "POST">
Customer Name:<input type = "text" name="customerName">
<input type = "submit" name = "submit">
</form>
session_start();
session_destroy();
You may also used unset() function for free up session Environment.
if (isset($_SESSION['user']))
{
unset($_SESSION['user']);
header('location:index.php');
}
Include this file in your header and set the required settings in file.
It should work well.
<?php
session_cache_expire(20);
if (!isset($_SESSION)) {
session_start();
}
// set timeout period in seconds
$inactive = 1200; // timeout for the session
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) {
$_SESSION = array();
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
header("Location: index.php"); // or whatever you prefer to do.
}
}
$_SESSION['timeout'] = time();
?>
If you aren't using the auth component then its really easy
public function logout(){
$this->Session->destroy();
// no cake we really want you to delete it because you suck
$this->Session->destroy();
}
//If you want complete destroy session then you can write.
session_destroy();
The session_unset() //function frees all session variables currently registered.
I have created an admin panel for a client in PHP, which requires a login. Here is the code at the top of the admin page requiring the user to be logged in:
admin.php
<?php
session_start();
require("_lib/session_functions.php");
require("_lib/db.php");
db_connect();
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: login_form.php');
die();
}
?>
Obviously, the if statement is what catches them and forces them to log in. Here is the code on the resulting login page:
login_form.php
<form name="login" action="login.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</form>
Which posts info to this controller page:
login.php
<?php
session_start(); //must call session_start before using any $_SESSION variables
include '_lib/session_functions.php';
$username = $_POST['username'];
$password = $_POST['password'];
include '_lib/db.php';
db_connect(); // Connect to the DB
$username = mysql_real_escape_string($username);
$query = "<grab username, hashed password from DB>;";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: login_form.php?login=fail');
die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
db_disconnect();
$hash = hash('<myHashingFunction>', $password . $userData['salt']);
if($hash != $userData['password']) //incorrect password
{
header('Location: login_form.php?login=fail');
die();
}
else
{
validateUser(); //sets the session data for this user
}
header('Location: admin.php');
?>
and the session functions page that provides login functions contains this:
session_functions.php
<?php
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['userid'] = $username;
}
function isLoggedIn()
{
if($_SESSION['valid'])
return true;
return false;
}
function logout()
{
$_SESSION = array(); //destroy all of the session variables
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
?>
I grabbed the sessions_functions.php code of an online tutorial, so it could be suspicious.
Any ideas why the user logs in to the admin panel, tries to do something, is forced to re-login, and THEN is allowed to do stuff like normal in the admin panel?
Be careful when using session_regenerate_id with redirects. In general. Don't.
remember to clear your browser cookies if the client switches servers :)
Is it just me, or is your isLoggedIn function really insecure? All you do is check for the existence of a session variable, which anyone could fake with a random value. You need to check the actual session ID/hash against a database of validated/logged in users.