I am trying to set the PHPSESSID from a value I received from a CURL POST. However, it is not setting when I assign it to the session_id(). The first echo statement is the correct PHPSESSID from the curl post. However, the second echo returns empty. Any thoughts?
PHP
//set current session id
session_id($sessID[1]);
echo "current SessID: " . session_id();
//start session
session_start();
echo "PHPSESSID: " . $_COOKIE['PHPSESSID'];
PHP's superglobals are populated with data when the script starts up, and then they are NOT touched again by PHP for the life of the script. Your new session ID will only show up on the NEXT request, after the new session cookie's had a chance to round-trip through the client's browser.
You cannot echo anything before doing session_start(). Per the docs:
Note: To use cookie-based sessions, session_start() must be called
before outputing anything to the browser.
http://us3.php.net//manual/en/function.session-start.php
The way you have it now is messing up the cookie. And you don't want to be messing up the cookies. :) The end result is the client never recognizes a session id cookie.
Related
On my secure site (https), I set a PHP $_SESSION variable. I then use header("location: http://...page.php") to send the user to a php page on my http site, which is on the same server. The session variable is lost, because of the http:// URL (I assume) in the header statement. I can't get the header("location: ...") to work without using the full URL. Thus I tried the following tip from stackoverflow - php session lost when switching, which several other posts reference, but I ended up with numerous error_log warning entries and once I clicked to another page that required $_SESSION['loginUser'], the session was gone.
PHP Warning: session_start(): The session id is too long or contains illegal characters
Sample session ID passed: dlouenopfi3edoep3dlvne8bn1
Code that creates the session on https php page (note for this post header location is not real)
session_start();
$currentSessionID = session_id();
$_SESSION['loginUser'] = $username;
header("location: http://www.test.com/path/to/page/off-campus/cat_index.php?session=$currentSessionID");
Code that receives the session on http php pages
// Retrieve the session ID as passed via the GET method.
$currentSessionID = $_GET['session'];
echo "sid: " . $currentSessionID;//a session id like above is displayed
// Set a cookie for the session ID.
session_id($currentSessionID);
session_start();
if(isset($_SESSION['loginUser'])){
$username = $_SESSION['loginUser'];
echo "Welcome: $username<br />";
} else {
require_once($_SERVER["DOCUMENT_ROOT"] . "/_includes/CASwrap.php");
}
I've exhausted my searching. Any help will be appreciated. Thanks.
I solved my two questions.
To prevent the numerous error_log warning entries all I needed was an "exit" statement after the "header" statement.
To maintain the current session, I used an if statement to test for a current session id stored in the variable $currentSessionID. If yes then set the session_id with the value of $currentSessionID. If no, then don't set the session_id with the $currentSessionID variable, since it has no value.
I made a simple registration page, which after validation, adds a unique identifier to the session id to identify the user and also sets a session variable 'UID' to a custom value. Then the script redirects to a new page.
$_SESSION['UID'] = $id;
session_id($sessID);
echo session_id();
session_write_close();
header("Location: https://localhost/AccountWebsite/landing.php");
exit();
?>
The landing page is supposed to be accessible only by members (i.e. those with a special unique session id set by my script), and that functionality wasn't working. So to check why, at the moment I allow anyone to access the page and their session id is echoed, and so is the 'UID' session variable.
<?php
session_start();
echo session_id()."\n";
echo $_SESSION['UID'];
?>
Now, when I echo the id it isn't the one I set myself. It is the generic PHP one, and the variable doesn't exist. During debugging, I commented out the redirect in the registration script, and instead had it echo the session id that it had just set. The echoed id is correct (obviously since it's echoed in the script it's set in), although when I enter the cookie manager on Firefox, it displays the session id as the generic php one, which means the session is reset when the first script ends and not between sessions.
Make sure session_start(); is called before any sessions are being
called. So a safe bet would be to put it at the beginning of your
page, immediately after the opening php tag before anything else.
Also ensure there are no whitespaces/tabs before the opening php
tag.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and
session_regenerate_id(true), you can try those as well, but I'd use
exit();)
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session
forward.
Make sure your file extension is .php (it happens!)
I have done all of the above from dayuloli's answer on this post
and have been debugging all day. Please help, why does the session not keep the id and variable values I set to it by the end of the script and sccross the whole server?
Additional info: I tried another example folder (on htdocs) where one page sets a variable and the other echoes it, and it worked.
You don't need to set a session_id unless you want multiple sessions. If you do specify a session_id, you need to call session_start() afterwards to start using it and submit the cookie into the client's browser.
Beyond that explanation, you need to use session_start() at the top of any script that requires sessions.
From http://php.net/manual/en/function.session-id.php:
session_id() needs to be called before session_start()
session_id() will always send a new cookie when session_start() is
called
I want to assign a value to a session variable when a user logs into a website. I read that I must explicitly start a session at the top of my pages in order to do this. So I inserted:
if (!isset($_SESSION)){
session_start();
echo "started";
}
The first thing I notice is that "started" is displayed every time I reload my page. Is that expected behavior? I would assume the second time I load the page, the session should already be there, therefore "started" would not display.
Further down in my page, I have:
$_SESSION['id']=2;
echo "<p>Your session ID is: " . $_SESSION['id'] . "</p>";
That correctly displays the ID in the "echo" statement. So even after assigning a value to a session variable, when I reload the page, it puts "started" at the top.
Am I doing something wrong? Thank you!
That is expected behaviour, you need to call session_start() before any output is sent to the browser every time the page is loaded, which is why your echo is happening every time. You if statement in this case is a little unnecessary and you should just simply call it without the if.
session_start();
For example, a $_SESSION variable will never be accessible unless you call session_start(), despite the fact that it will exist in the browser's session. Calling session_start() simply allows you to access that superglobal array.
You need to put your session_start() at the top of the file.
Otherwise you won't be able to use the $_SESSION array.
I am trying to implement a login system with a 'remember me' feature . This is my my login page: http://pastebin.com/q6iK0Mgy . In this I am trying to extend the session cookie(PHPSESSIONID) expiration using session_set_cookie_params() . But its not working.
Relevant portion from the code: In this the inner if() loop is being executed , but session_set_cookie_params('3600') is having no effect. I am calling session_name() , as it is supposed to be a requirement for session_set_cookie_params() (according to one of the comments on php manual)
if ( isset($_POST["submit"]) )
{
session_name() ;
echo "calling before checked " ;
if ( $_POST["remember"] == "on")
{
// extend expiration date of cookie
session_set_cookie_params('3600');
echo "<br/>calling after sessions_set_cookie_params" ;
}
}
require_once("includes/session.php"); //session start ?>
I hope I was able to explain what I want to do. Basically what I a trying to do is extend the session_cookie's expiration. is my way of doing completely wrong? is there another way to achieve the same ?
thanks
Never too old for an answer right?
So, PHP is dumb. As in, it doesn't do what you think would make sense.
session_set_cookie_param will not do anything until the exact moment that you call session_start. So if you set cookie params after calling session start, too late. If you set the cookie params but then don't call session_start, nothing happens.
session_start is also a funny beast. It only reads cookie data the first time it is called -well that is unless.... you force it to write, or there is no cookie to begin with. So if there is no cookie, it writes the cookie data and the client saves your session. yay! But when the cookie exists already, how to we force it to write, and therefore update our new expiry date??
So, we have this odd effect of ignoring all of your session_set_cookie_param calls if a cookie already exists on the client. Even better, if you explicitly call setcookie(session_name(),blah blah blah), php will STILL not emit the cookie.
So, let's force php to emit a cookie.
option 1
This works by calling session_id with the only value that won't clobber your existing session. Documentation at http://php.net/session_id states that
Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.
session_id($_COOKIE[session_name()]);
So anyways it's 6 in the morning and I haven't slept yet and you probably figured this out months if not years ago, but what the hell, maybe i'll save someone else the 2 or 3 hours of my life i'll never get back. ha ha.
From the documentation:
You need to call
session_set_cookie_params() for every
request and before session_start() is
called.
Also check http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime
I wrote a little PHP script below to demonstrate my question. Run the code below like this: http://localhost/test.php?test=10, then run http://localhost/test.php?test=11, then http://localhost/test.php?test=12, etc. You will see that the number echo'ed to your screen is always 1 digit behind the url number?! Maybe because I cant a cookie and immediately read the same cookie?
//If query string has $test, store in session, and cookie for later.
if($_GET[test]){
$_SESSION['test'] = $_GET[test];
setcookie("test", $_GET[test], time()+60*60*24*30*12*10); //10 years
}
//If user comes back later, then get $test from cookie
if (isset($_COOKIE["test"])){
$_SESSION['test'] = $_COOKIE["test"];
}
echo "session test: " . $_SESSION['test'];
Later, I solved the problem with the following code, but solving it is not good enough, I want to know WHY this happened!
This solved it:
if($_GET[cid]){
setcookie("campaignid", $_GET[cid], time()+60*60*24*30*12*10); //10 years
$_SESSION['campaignid'] = $_GET[cid];
}elseif (isset($_COOKIE["campaignid"])){
$_SESSION['campaignid'] = $_COOKIE["campaignid"];
}
Maybe because I cant a cookie and immediately read the same cookie?
Exactly. The cookie you sent is available in $_COOKIE array only in the next request, because the $_COOKIE superglobal array is filled with the data, that comes in the client's request. And at first request it is nothing.
Technically you didn't start a session (session_start()) and you're using undefined constant test, however PHP is "intelligent" enough to figure out you mean a string "test".
What's exactly the question?
Maybe because I cant a cookie and immediately read the same cookie?
Yes, that's true. You've just proved it.
In your first snippet you are calling setcookie(). This sends a HTTP header to the browser. PHP does not update the $_COOKIES variable when you call setcookie(). The $_COOKIES variable is updated on the next script invocation, when the cookie is returned by the browser.