I have been beating my my head over this. My code is virtually identical to other projects where this DOES work. Here is how I do it:
session_start();
set_up_session($username);
redirect_to('index.php');
And the two functions:
function redirect_to($location=null) {
if($location!=null) {
header("Location: {$location}");
exit;
}
}
function set_up_session($username) {
session_start();
$_SESSION['user_id']=$id;
$_SESSION['logged_in']=true;
$_SESSION['username']=$username;
}
if I comment out the redirect and echo any of the $_SESSION var's, the var reads correctly. But after the redirect, the session ends.
This is what's on the next page.
<?php if (!isset($_SESSION['logged_in'])) { ?>
// do stuff <-- this is what gets shown showing session is no longer active
<?php } else { ?>
<p>Hi, <?php echo $_SESSION['username']; ?></p>
<?php } ?>
make sure the page you are redirecting to has session_start() at the top of the document
if(!isset($_SESSION)){
session_start();
}
My first step I would do is try this on the next page:
<?php
if (isset($_SESSION['logged_in'])) {
echo $_SESSION['username'];
} else {
//do stuff
}
?>
I had a problem a posted earlier in dealing with sessions. My resolution to the problem was to set a $_SESSION[]; to a variable. EX:
<?php
$Username = "Guest"; //Set your variable before you actually need it. (This is what fixed my problem)
if (isset($_SESSION['logged_in'])) {
$Username = $_SESSION['username'];
}
?>
NOTE: You might want to change the if (isset($_SESSION['logged_in'])) to instead check for if the username is set. For example:
<?php
$User = "Guest";
if (isset($_SESSION['username'])) {
$User = $_SESSION['username'];
} else {
//do stuff
}
?>
Also, as stated by the other user, make sure the page you redirect to has a session_start(); function in it. Otherwise, this will not work.
Related
I am having an issue with the follow code. It can echo the variables before it redirects, no problem. But after it redirects, it cannot. It seems to be losing the session variables in the redirect process. Any thoughts?
Original Page:
if (password_verify($rawpassword,$row["passwordHash"])) {
session_start();
$_SESSION["email"] = $email;
$_SESSION["fname"] = $row["firstName"];
echo $_SESSION["email"];
echo $_SESSION["fname"];
header("Location: https://www.mywebsite.com/home.php");
} else {
header("Location: https://www.mywebsite.com/signin.php?addlComment=3True");
die();
}
The Following Page:
<?php
echo $_SESSION["email"];
echo $_SESSION["fname"];
?>
You should learn more about sessions to avoid making mistakes and not leaving your codes vulnerable!
Know that to work with sessions, you must start them right at the beginning of each script
Also, after you create your session, you don't need to use the 'echo' command and right after redirecting to the success page, in fact, it is on the success page that you should work with the 'echo' command, and create some variables to store the value of those sessions, to make it easier to work with, and to make the code cleaner!
Please try it:
Signin
<?php
session_start();
//Start the session in the top of the script
if (password_verify($rawpassword, $row["passwordHash"])) {
$_SESSION["email"] = $email;
$_SESSION["fname"] = $row["firstName"];
header("Location: home.php");
exit();
} else {
header("Location: signin.php?addlComment=3True");
exit();
}
Home
<?php
session_start();
session_regenerate_id(true); //It can help you to protect against attacks, try to learn it!
$email = $_SESSION['email'];
$first_name = $_SESSION['fname'];
//If the user try to access the page without make login, then redirect to the signin page
if(!email || !first_name)
{
header("Location: signin.php");
exit();
}
//Test the sessions variables
echo "Welcome, you're logged in! I know your first name is: {$first_name}";
I am new to php, and I want to know if it is safe to do it like this...
I currently have a login system to protect a few pages.
Is it possible for a hacker to change the value of $logged_in?
Is this safe?
If it isn't. what is the best way to do it?
Files:
- not_logged_in.php
- test.php
- login.php
- logout.php
- protected_page_1
- protected_page_2
- unprotected_page_1
Code:
not_logged_in.php:
<html>
You are not logged in!
</html>
test.php:
<?php
$logged_in = false;
function protect_page() {
if($logged_in == false) {
header('Location: index.php');
exit();
}
}
?>
login.php:
<?php
include "test.php";
$logged_in = true;
?>
logout.php:
<?php
include "test.php";
$logged_in = false;
?>
protected_page_1.php:
<?php
include "test.php";
protect_page();
?>
<html>
Content
</html>
protected_page_2:
<?php
include "test.php";
protect_page();
?>
<html>
Content
</html>
unprotected_page_1:
<html>
Content
</html>
I completely understand that the login.php page just logs in and you don't have to give in a password, but that is just for testing currently...
Thanks for reading!
I think the way of using this $logged_in variable is too loose.
I suggest to make use of sessions.
session.php:
<?php
session_start(); // start on top of your page before any output
if(!isset($_SESSION['loggedin'])) {
$_SESSION['loggedin'] = false;
}
function loggedin()
{
return $_SESSION['loggedin'];
}
?>
and in any page with protected content.
<?php
include 'session.php';
if(!logged_in()) {
include 'login.php';
exit();
}
// some info
?>
login.php will have a form to log in. (and to $_SESSION['loggedin'] = true;
every page could include session.php.
Yes, it's protected. Maybe you can store the variable that shows weather the user is logged or not in a session storage to make it even more efficient.
session data not displaying on logging in for the 1st time but its displaying once logging out and logging in again.
Anything can i do to display session data on example.com/page2.php on logging in for the first time ?
example.com/page1.php
<?php
session_start();
$_SESSION['id'] = 1;
$_SESSION['name'] = 'dummy name';
$_SESSION['email'] = 'dummy#dummymail.com';
header("Location: http://example.com/page2.php");
?>
example.com/page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
session_start();
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>
example.com/logout.php
<?php
session_destroy();
header("Location: http://example.com/page1.php");
?>
You should call
session_write_close();
before
header("Location: ...");
to ensure that the session data set in page 1 is written to disk before page 2 is requested.
In addition, it seems that using
header("Location: ...");
on page 1 will leave the $_SERVER["HTTP_REFERER"] value unset on page2.php. I tested this by changing page2.php to
<?php
echo "<pre>";
echo htmlspecialchars(print_r($_SERVER, true));
echo "</pre>";
if ($_SERVER["HTTP_REFERER"] == "http://example.com/page1.php")
{
session_start();
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
}
?>
Logout
If you try the same you may see that
[HTTP_REFERER] => http://example.com/page1.php
is not listed in the $_SERVER array on page 2.
On page 1, just to test, instead of using
header("Location: ...");
try using
echo 'Page 2';
and you should find that when you request page1.php then click on the Page 2 link, $_SERVER["HTTP_REFERER"] value will be set on page 2.
So is seems that your problem may include redirection not setting $_SERVER["HTTP_REFERER"]. Once you change your scripts to resolve this issue you may have a better change or sorting out the session issue.
You might like to try
page1.php
<?php
session_start();
$_SESSION["id"] = 1;
$_SESSION["name"] = "Dummy";
$_SESSION["email"] = "dummy#example.com";
session_write_close();
header("Location: page2.php");
?>
page2.php
<?php
session_start();
if (isset($_SESSION["id"]) && ($_SESSION["id"] == 1))
{
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
echo 'Logout';
}
else
{
echo 'You are not logged in. Login';
}
?>
logout.php
<?php
session_start();
$_SESSION = array();
session_write_close();
echo 'You have been logged out. Login Test login status';
?>
I know this is necroing a 4 year old thread, and you were not having the exact situation but here's what I found:
I was having a problem with my welcome message saying 'Welcome, [user]!'. I couldn't get it to display until I logged out and logged in again, similar to your question title.
<?php
//says "Welcome, (whatever the user's name is)!"
$welcomemessage = "Welcome, " . $_SESSION["user"] . "!";
if ($_SESSION["loggedIn"] === 'y') {
echo $welcomemessage; }
?>
On my change username page, I changed the session variable to my new username, like so:
$_SESSION["user"] = $newusername;
which is changing it from the initial username, since your old username would be set as the current session variable even if you've changed it.
So, if I change my username from John to Jeff, anything which would mention John will be changed to Jeff immediately as the 'new username' variable is displayed, rather than having to log out then log in for the code to take your new username from the database and display it.
I know this won't help you as it's been 4 years, but this was the closest question I could find to my problem and wanted to share my simple solution for anyone else who looks this up :)
You forgot session_start() on your logout.php.
<?php
session_start(); //<------- Here
session_destroy();
header("Location: http://example.com/page1.php");
?>
and comment this on page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
//session_start(); <----- Comment this as shown
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>
I've a problem with PHP sessions.
This is my code:
login.php
<?php
session_start();
...
...
...
$_SESSION['id'] = $user['id'];
$_SESSION['name'] = $user['nome'];
$_SESSION['ruolo'] = $user['ruolo'];
$_SESSION['auth'] = true;
header("location: index.php");
exit();
...
...
index.php
<?php
session_start();
var_dump($_SESSION);
...
...
?>
result is array(0) { }
I've already seen other similar posts, but no proposed solutions are helpful to me (session_start, exit after header, etc)
Some suggestions?
Try adding this to the top of your script:
ini_set("session.cookie_domain", ".domain.com");
I'm trying to create a simple member login site, and I was following along with a tutorial online. However, a deprecated function is used. Here is the code.
<?php
session_start();
session_destroy();
if(isset($_COOKIE['id']))
{
//remove cookie
setcookie("$id_cookie", '', time() - 50000);
setcookie("$pass_cookie", '', time() - 50000);
}
if(!session_is_registered('username'))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>
I also tried !isset($_SESSION['username']), but every time I try to log out, I just receive the 'Sorry we could not log you out' text.
Here is the part of my login.php file code where I set the sessions:
//member does exist, start sessions
$_SESSION['password'] = $password;
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
Any help would be great!
Don't use
session_is_registered
use
if (isset($_SESSION['SESSION_VARIABLE_NAME']))
You may add "session_unset();" before "session_destroy();"
session_destroy() delete the session file and release the session id, but keep the $_SESSION variable in memory.
use this with isset
if(!isset($_SESSION['username']))
Try this
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
Check where the the SESSSION is stored or not.
Try this code in your log out script
<?php
session_start();
if(isset($_SESSION['id']))
{
unset($_SESSION['username']);
unset($_SESSION['id']);
}
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>