So I have a problem where I have several $_SESSION values defined and need to be sent to the next page. Here is a quick look at the meat of my problem.
login.php
session_set_cookie_params(900, '/', 'localhost:8080/test/');
session_start();
$_SESSION['first_name'] = "Moe";
$_SESSION['last_name'] = "Joe";
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/test/admin_console.php?" . SID);
exit();
?>
On the next page, I expect my $_SESSION['first_name'] and $_SESSION['last_name'] to be defined as they have been set by the code above. The following is the meat of my code in the next page
admin_console.php
session_name('AdminLogin');
session_start();
#Set page title and include HTML header
$page_title = 'Administrative Console';
include('./header.inc');
$mysession = session_get_cookie_params();
$msg = $_SESSION['first_name'];
echo "Is the thing set? " . $msg . "<br />";
?>
The problem is, i get the following error:
*Notice: Undefined index: first_name in C:\wamp\www\test\admin_console.php on line xx*
I can't for the life of me figure out why $_SESSION['first_name'] wont retain its value from previous page. i have session_start() in every page and i even went as far as to add several lines to completely kill the session at the end of this page
<?php
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-300, '/', '', 0);
?>
So my echo statement should display the value that is entered in $_SESSION, but to no avail. Any help?
OH MY GOD, it is the worst mistake in the world.
Google Chrome, for some reason, saves previous attempts or pages. So during my initial tests, the page failed. But when I fixed the code, the browser still retained the old style.
I just now had this feeling in my gut to try the code in the Incognito mode, and it WORKED!
Lesson Learned: If your code looks perfect and you're still getting same error no matter what, try a different browser or clear out browser cache.
It's just a notice (warning). You can set error_reporting(7); to get rid of this message.
Your code looks fine , check your php info "session section".
Related
PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?
I'm pretty new to PHP and I'm struggling with my webshop.
I have a drop down menu on my site with one menu option containing all product categories in the webshop. As long as I'm navigating between these categories my session is persistent and working fine (I'm putting products in a shopping bag and I can move to the cart and go through with the whole order). But if I go to a page in another drop down menu option "outside" the webshop (like the contact page) my session is lost. I have used pretty much the same template to create these pages, but they are of course more simple with mostly text content (apart from the cart that is always accessible from the top menu).
The first page outside the webshop drop down menu option is ok with the correct session id, but when I move to the second page the session is gone. It doesn't matter in which order I visit the pages. The first one is always working but the following ones are not.
What on earth can be causing this behaviour? On every page I start with this piece of code:
<?php
session_start();
?>
<!DOCTYPE HTML>
...
Further down I include the cart in the top menu:
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/includes/right-cart.inc";
include_once($path);
And in the included cart code I use this line for the session id:
$currSession = session_id();
Any ideas?
EDIT 1:
I tried to add some error logging and noticed something interesting. I now start my files with this (just to find out some more information):
<?php
phpinfo();
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
// create session variable if it doesn't exist yet
if (isset($_SESSION['counter']))
$_SESSION['counter'] ++;
else
$_SESSION['counter'] = 1;
var_dump($_SESSION); echo "<br/>\n";
var_dump(session_id()); echo "<br/>\n";
var_dump(session_name()); echo "<br/>\n";
var_dump(session_get_cookie_params()); echo "<br/>\n";
?>
As long as I have the first row, phpinfo();, the session seems to be the same. But if I remove that line the session keeps renewing when refreshing the page...
EDIT 2
After a suggestion I tried to use a cookie to store a "session id" instead of a regular session. The code at the top of my page now seems like this:
<?php
session_start();
$currSession = "";
$cookie_name = "sessionId";
$cookie_value = "";
if(!isset($_COOKIE[$cookie_name])) {
$cookie_value = session_id();
setcookie( $cookie_name, $cookie_value, time() + (60*60*24*2), "/");
}
if(count($_COOKIE) > 0) {
$currSession = $_COOKIE[$cookie_name];
} else {
$currSession = session_id();
}
?>
But everytime I reload the page also the cookie value seems to change. I have tried different echo statements in the code to verify what happens but everything looks right (the cookie is created successfully, the isset function tells me that the cookie actually is set etc), but still the value in the cookie changes. Any ideas?
I finally solved the question so I thought I'll post the answer here in case someone else is having trouble.
I changed this line ("/"):
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), "/");
to ('/')
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), '/');
and suddenly it works! :-)
I have a log in form that allows persistent login and regular session. Long story made short, when users are in their account, they can change password, email and stuff. But for that, I need to get their username from their session or cookie first (so I can do the proper SQL query).
I try to do so with this code:
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else
if(isset($_COOKIE['username']))
{
$username = $_COOKIE['username'];
}
But if I try to echo $username, I keep getting "undefined variable". Why is that?
I noticed that if I put a session_start(); at the top. I get the proper username for session but not for cookie of course. How can I solve that?
The weird part (for me) is that I got the exact same code (well that part) in another page and username isn't undefined.
PS: If something isn't clear or more information is needed, please tell me.
EDIT
I tried this:
function accountValidation()
{
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']))
{
$cookie = $_COOKIE['username'];
$explode = explode(' - ', $cookie);
$username = $explode['0'];
}
echo $username;
}
accountValidation();
And it worked ... So if I put it into a function and then call it, it works?! What is the diference? Why does it need to be into a function for it to work???
If you set certain cookie, it would be available to you from next reload. As $_COOKIE is set when a page head is called. You wont be able to retrieve the cookie from the same page which has set the cookie. I hope you got what i meant. If not let me know I would give an better example.
EDIT:
Example
<?php
session_start();
$_SESSION['test'] = 'test1success';
echo $_SESSION['test'];// would display test1success
if (!isset($_COOKIE['test2']))
{
setcookie("test2", "test2success", time()+3600);
}
echo $_COOKIE['test2'];
// wont display test2success when you load the page for first time
// reload it & it would display test2success
?>
Explanation:
The first thing you need to understand is that the cookie is stored on your PC(browser) when the page is loaded. The client (i.e. browser) sends cookie headers to the server & does the page execution. The values set by set_cookie during page execution are set on the client pc, and the server doesn't know about the new values just set - unless you reload the page & the cookie header is sent back.
I'm new to PHP and havn't worked with sessions before, I have read up on it a bit and understand what they do and how i should be able to use them.
When I create my session however, it seems to create the session fine (code gets run and if I look into cookies I can see entries from my website)
I can also set $_SESSION values on the same page, but as soon as I enter a different page, the session is reset it seems.
Here's my code:
$sessionid = md5(uniqid(microtime()) . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
ini_set('session.auto_start', 1);
ini_set('session.lifetime', 2678400);
ini_set('session.use_cookies', 1);
ini_set('session.cache_limiter', 'private_no_expire');
session_start($sessionid);
// Also tested that setting these doesn't give an error either
$_SESSION['Username'] = //Code to get username
$_SESSION['UserID'] = // Code to get userID
echo "<script language='Javascript'>";
echo "window.location='" . $forwardpage . "';";
echo '</script>';
exit();
Any help would be appereciated
The problem is that every time you load the script a new session id is created and sent to the client.
Skip the $sessionid variable and php will generate a sessionid for you and it will work.
So, use session_start() without $sessionid
Hello i am having problems holding sessions from page to page, code worked on my previous servers running php5 but not on my recent server, i am wondering whether its a bug?
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
ANy ideas? session is held on first page but not on the second.
In case you missed it, make sure you do a session_start() at every page you're using the $_SESSION variable.
You should check your php.ini file and see what's going on.
Make sure session.use_cookies = 1 and session.save_handler = files.
Use this test page to see whether it's a general PHP problem or just your code.
<?php
session_start();
if(isset($_SESSION)){
echo "Session variable exists<br/>";
if(!isset($_SESSION['test'])){
$_SESSION['test'] = "Success!";
echo "Variable has been set, refresh the page and see if stored it properly.";
}else{
echo $_SESSION['test'];
}
}else{
echo "No session variable has been created.";
}
?>
If that worked, then it's got to do with your code.
If you're setting your session variable to $_POST['session'] am I to assume you submitted a form with an input with the name session?
This setup should work.
index.php
<form action='page0.php' method='POST'>
<input type='hidden' name='session' value='SPAAAAACE' />
<input type='submit' />
</form>
Page0.php
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
Page1.php
<?php
session_start();
echo "Good morning" . $_SESSION['session'];
?>
For completeness and debugging purposes
In case you are using cookie-less sessions, you have to manually add the SID (session id) to the header redirect like this
header("location: www.mysite.com/page.php?".htmlspecialchars(SID));
If the problem still persists, it could be a permission issue.
Maybe you're not allowed to read the session file stored on the server?
Update: OP commented that it was a permission issue and the problem is now resolved
Turn on error reporting temperately with:
error_reporting(E_ALL) This may spit out an error related to your problem. Most likely an undefined index session notice.
You should always have a check in place on Super Globals.
<?php
session_start();
$_SESSION['session'] = (isset($_POST['session']))?$_POST['session']:null;
header("Location: www.mysite.com/page1.php");
die;
?>
Your code seems correct though I'm pretty sure $_POST['session'] is empty.
You should try this :
<?php
session_start();
$_SESSION['session'] = 'John Doe';
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
To see if this works or not. I guess it will.
IF not, take a look at your cookies, maybe they are disabled.
Then, if it works, I probably because $_POST['session'] is null or empty, are you sure you posted something like <input type="text" name="session" /> ?
You need to pass the session id with the redirect.
Also make sure you use session_start() at the top of EVERY page that needs a session
First try using
<?php session_start();
instead of
<?php
session_start();
If the problem still exists, then open your script in Netbeans editor and see whether any unexpected characters found at very beginning of the the script.
In addition, please make sure that $_POST['session'] has a value to assign in $_SESSION['session'].
You will have to call
session_start();
on the first line of every page you want to retain the session in