Session cookie is reset to default at the end of the script - php

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

Related

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

Using $_SESSION between pages that are in different directories

I was wondering how I would pass something using a session between pages that are in two separate directories. For example, if I had the following code, what would I need to add to make it work?
Page 1: directory\directory1\directory2\Page1.php
session_start();
$_SESSION['example'] = '123';
Page 2: directory\dir1\dir2\Page2.php
session_start();
echo $_SESSION['example'];
Your code should work if these pages are served within the same domain.
You do not have to session_start() in each page. Just write that, in a single file and share that file between the pages you want to hold the session in.
So, if you have page1.php and page2.php and session.php You can create session either in page1.php and check it in page two like: echo var_dump($_SESSION) and vise-versa
First of all, check if session-cookies are properly set. Some problems (e.g. Headers already sent) may cause your session cookie to not be set.
If this is working properly, you may have to change the session cookie parameters via session_set_cookie_params
By setting the second parameter (path) to /, the session cookie is valid for the root of your website and all subdirectories.
Example
session_set_cookie_params(0, '/');
The same settings can also be set in your php.ini or via ini_set(). See Session configuration
Note:
I'm not sure if these settings have any effect if session.autostart is enabled, in which case the cookie-header may already be sent before the changes are made.

php session pass with setcookie and unset

i have a strange problem, when i use setcookie in PHP with session, while my browser is open, everything work fine, but when I close it, then I can't pass $_SESSION from page to another page!
in login page I have:
$_SESSION['name'] = $_POST['name'];
$_SESSION['pass'] = $_POST['pass'];
$life=2592000;//1 month
setcookie(session_name(),session_id(),time()+$life);
header("location:administrator/");
die();
I used session_start(); in every page on top of them, also I used this code for logout:
session_start();
unset($_SESSION['name']);
unset($_SESSION['pass']);
session_destroy();
header("location:../");
an important note is when I checked browser cookies, before closing browser there are tow cookie and their contents value is exactly same like each other, one expire at the end of session but another expire one month latter, which I like to be, but then I close browser and return back, there are tow cookie but with different values! which I think case problem and session variables don't pass from page to page.
Apart from the problem mentioned by #Matt (you may need some custom mechanism to restore or reinstantinate session using cookies), keep in mind that using mod_rewrite or actual directories messes with cookies path! To make sure the cookie is available when and where you need it, add additional parameter / (PHP setcookie(), $path parameter)

Categories