Logout is not working [duplicate] - php

This question already has answers here:
proper way to logout from a session in PHP
(4 answers)
Closed 7 years ago.
I have a logout button which doesn't seem to work well. After clicking on it I can still see the "Welcome username" and the logout button is still there as in the picture below. Please let me know what's missing on my logout.php.
May I also ask how I could redirect the user back to the orginal page after clicking logout ? I try to use "header('Location: ' . $_SERVER['HTTP_REFERER']);" but it doesn't work ?
Index.php
<?php
ini_set("session.save_path", "sessionData");
session_start();
?>
<?php if (!isset($_SESSION['uName'])) { ?>
<form method="post" action="logonProcess.php">
<div>Username <input type="text" name="userName" placeholder="Username"></div>
<div>Password <input type="password" name="pwd" placeholder="Password"></div>
<div><input type="submit" value="Logon"></div>
</form>
<?php } else { }?>
<?php if (isset($_SESSION['uName'])) {
$username = $_SESSION['uName'];
echo "<p>Welcome $username</p>\n";
?>
Logout
<?php } else { }?>
Logout.php
<?php
unset($_SESSION['user']);
session_destroy(); // Destroying All Sessions
header("Location: index.php"); // Redirecting To Home Page
?>

Try starting session first:
Logout.php
<?php
session_start();
unset($_SESSION['uName']);
session_destroy(); // Destroying All Sessions
header("Location: index.php"); // Redirecting To Home Page
?>
source from: http://www.hackingwithphp.com/10/3/5/ending-a-session

try adding this to your logout file:
unset($_SESSION['uName']);

All your scripts that use sessions need to use the same session.save_path setting. Since you set that in index.php, you also need to set it in logout.php. Otherwise, logout.php won't be able to access the session data.

Related

Redirect not working with header("Location:

I've searched but can't seem to figure this one out. I have a config.php which searches for an active session and if found passes the user through, if not it fowards to the login.php page. The config.php also grabs the orginal URL and posts to login.php so we can redirect them to the page they were going to originally.
From there it should be pretty simple, authenticate and then use the redirect variable to forward browser to original page. But it's not working like that. It forwards me back to the login.php and says "Object Moved". Its redirects if I put header("location: /index.php"); but not if I use the variable in the login.php like below.
Any help would be appreciated!
PHP (config.php):
<?php
session_start();
// put somewhere in a config file
define('SESSION_EXPIRE',3600); // in seconds
// check passage of time, force log-out session expire time
if(isset($_SESSION['last_activity']) && (time() - strtotime($_SESSION['last_activity']) > SESSION_EXPIRE)) {
// destroy session
session_unset();
session_destroy();
}
// if user is logged in and unexpired, update activity
if(isset($_SESSION['user'])) {
// user is logged in
$_SESSION['last_activity'] = date('Y-m-d H:i:s');
}
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
?>
PHP (login.php):
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// get orginal URL from config.php
$url = $_GET['location'];
// check to see if login form has been submitted
if(isset($_POST['userLogin'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("location:".$url);
die();
} else {
// authentication failed
$error = 1;
}
}
// output logout success
if (isset($_GET['out'])) echo "Logout successful";
?>
HTML:
<div class="panel-body">
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="userLogin" type="Username" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="userPassword" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<input class="btn btn-lg btn-success btn-block" type="submit" name="submit" value="Login" />
</fieldset>
</form>
</div>
I am not sure if I understand your exact problem but if you are trying to redirect to $location and it is not going to the proper page or throwing an error then you may need to urldecode it before passing the variable.
in your config you encode the URI:
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
So in your Login decode it:
$url = urldecode($_GET['location']);
As mGamerz said make sure that your header has a capitol L and a space after the colon
header("Location: ".$url);
You need to remove login.php from here: action="login.php" You're losing the $url variable because it's not being included in the GET after the page posts back to itself.

PHP Session won't keep array variables

I have an Index page with login form, a verification page called Login and content.
Index is fairly simple: if logged in, redirect to Content, otherwise display login form and POST to Login page
index.php:
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');
} else {
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="POST" action="login.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="usr"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
<?php } ?>
Then we have Login verification: compare the POST vars with coded variables, if all is good, set Session variables and redirect to content.
login.php:
<?php
session_start();
if($_POST['usr']=='user' && $_POST['pswd']=='password'){
$_SESSION['usr'] = 'user';
$_SESSION['pswd'] = 'password';
header('Location: content.php');
} else {
echo "post: ";
print_r ($_POST);
//header('Location: index.php');
}
?>
Then we have the Content page, check that the Session is set and display content, otherwise PRINT_R
content.php:
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
The process works, up to the Content page. I keep getting a blank SESSION array, and when I try going to Index, it pretends I never logged in. what am I missing?!
Edit: in The code above, content.php is trying to check if the session is set. If it is NOT set it will show me a blank array (for debugging purposes, but normally I want it to go back to index, since the user is not properly connected),
if it IS set, it will echo "you are logged in". It is also including a page called 'logoff.html' as that page has a button to destroy the session.
Even without the IF statement, simply running a print_r ($_SESSION); returns a blank array. This means there is no problem in the IF statement, but something that happens before it.
Solution: I didn't know about this before, but some hosting sites require some PHP set up, before they can store PHP sessions. I went to the knowledge base of my hosting service and searched for "session", and found an explanation on how to set up the php.ini file to save my sessions in the correct path.
Make sure sessions are configured properly. For example, is the session save handler set correctly? If using files, does it have permission to access the specified folder? If memcache, is that set up properly?
This would be the main reason for session variables to not be saved.
change this
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
i think in your code when session not set then it will print so change it with
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd']))
{
// session is set
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
}
else
{
/// session is not set
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>

After checking session it is not redirecting to another page

Here is my code in which i am checking if session variable is not set then it will redirect to another page:
if (!isset($_SESSION)) {
session_start();
}
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779"); 
}
Problem: It is not redirecting to another page BUT if i change this line
header("location: http://myweb.com/rel_notes/?page_id=779"); 
to
die("You aren't allowed to access this page");
then it works. So Kindly tell me why it is not redirecting to another page?
EDIT: This is my whole code of that wordpress page im currently working on:
<?php
ob_start();
session_start();
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
exit();
}
if (isset($_POST["cancel"]))
{
if (!isset($_SESSION)) {
session_start();
}
session_unset();
session_destroy();
header("location: http://myweb.com/rel_notes/?page_id=779");
exit();
}
?>
<form method="post" enctype="multipart/form-data">
<div align="right">
<input class="btn btn-primary" type="submit" value="Log Out" name="cancel" id="cancel" style=""/>
</div>
</form>
Try like this. If this is just the code it will work fine.
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
}
If you have any other code after this you may get headers already sent notice.
EDIT :
You can even achieve this using JS. [However , I personally don't recommend]
<?php
session_start();
if (!isset($_SESSION['username']))
{
//header("location: http://myweb.com/rel_notes/?page_id=779");
echo "<script>document.location.href='http://myweb.com/rel_notes/?page_id=779'</script>";
exit;
}
Is there any output above this code? header("location: ..."); works only if there was no output yet. If you need it nonetheless, add ob_start(); at the top of your script.

How to stop people accessing hidden pages where a login is required?

I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

$_SESSION for users on forums or stackoverflow

Suppose that I have also coded a similar login form then issue the session by name via $_SESSION['name'] as follows
session_start();
if(!isset($_SESSION['name'])){
header("Location: login.php");
}
then right on the same file (display.php) I also display a form to post a message to the administrator to tell him about how I feel such as
<td>
<form action="tellhim.php" method="POST">
Title:<input type="text" col="30" name="comment_title"/><br/>
Your feeling:<br/><textarea name="comment_content" col="10"></textarea><br/>
<input type="hidden" name="postfeeling" value="TRUE"/>
<input type="submit" value="Submit"/>
</form>
</td>
that means, right after I click the button to submit my feeling I will be directed to tellhim.php. The problem then is that the session seems invalid right after the page is reloaded. Could someone help me out please ?
You should exit(); after header()
file tellhim.php needs that also:
session_start();
AND the session_id has somehow to be added to tellhim.php, automagically like this:
ini_set('session.use_cookies', 1);
ini_set('session.use_trans_sid', TRUE);
ini_set('url_rewriter.tags', 'a=href,area=href,script=src,link=href,frame=src,input=src,form=fakeentry,form=post,form=action');
session_start();
You need to use session start() before all the files that you want to use
//login.php after login redirect to display.php
session_start();
//set session variable
$_SESSION['name'] = 'xxx';
//display.php
session_start();
if(!isset($_SESSION['name'])){
header("Location: login.php");exit;
}
{rest of the form code goes here}

Categories