Php session not creating correctly - php

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

Related

PHP session is not resuming

I have a problem with sessions in PHP. When I use session_start(), and assign a value using $_SESSION['x'] = "Y", the value is gone after refreshing the page (session is empty). echo session_id(); always shows a different value. I also tried using exit() after assigning the value. This probably means that the session is not resumed, a new one is created instead. What can I do?
EDIT: I am using cloudflare, might this be a problem?
My code:
<?php
session_start();
echo session_id();
exit();
It always shows something different. PHP session is created in /var/lib/php/sessions, but php session cookie is not set, cookies are enabled in my browser. I have also tried a different browser.
EDIT 2:
When I refresh the page, a new session file is created.
The only cookie is __cfduid. I think it's something with cloudflare.
EDIT 3:
I have also tried without cloudflare. My PHP sessions settings are default.
session_start(); echo session_id(); $_SESSION['x'] = "Y"; echo '<br>'; echo $_SESSION['x'];
if your cookies are disable then your session_id() create every time new. please make sure cookies are not disable.
It's old, but the problem is very simple:
Your cookie need to be marked as secure!
Look this solution:
PHP Session ID changing on every request
Setting $_SESSION value NULL is working on this example.
<?php
session_start();
function errorMassage()
{
if (isset($_SESSION["errorMassage"])) {
$outPut = "<div class =\"alert alert-danger\">";
$outPut .= htmlentities($_SESSION["errorMassage"]);
$outPut .= "</div>";
$_SESSION["errorMassage"] = null;
return $outPut;
}
}
?>

How to find out that session has expired in PHP?

I'm trying to improve the session management for web applications. My major issue is the session expiration and how to deal with it. For that I'd like to find out if the session is still available or not. I'm using the default file based sessions (PHP 7.1, Apache 2.4, Fedora/RHEL) and it is cookie based.
What I've found out is that the session GC gets executed when session_start() is called. It is not with the begin or end of the script execution, it happens with this function. What seems odd to me is that if session_start() and the GC consider the session as expired and want to delete the corresponding session file, $_SESSION gets populated regularly first, then the file will be deleted. That's surprising.
With that behaviour only the next following request leads to an empty $_SESSION. I would expect this with the call before - the one that deletes the file. So if I'd like to know whether the session has expired in the current request I would have to check if the session file still exists after the session_start() call. That seems strange to me.
Are there any other or better ways to check that a session has expired than looking into the file system?
I thought I could just check if $_SESSION is empty to determine that the session was renewed - but that is obviously not possible.
Update: I've found the following bug reports dealing with the issue: this and that. There's also a SO entry about the expiration problem. Current PHP source: php_session_start calls php_session_initialize calls php_session_gc.
You may want to play with this script (unreal settings are just for testing purposes):
ini_set('session.gc_maxlifetime', 2); // Session gets expired after 2 seconds
ini_set('session.gc_divisor', 1); // Delete expired session files immediately
ini_set('session.save_path', '/some/safe/path/for/testing'); // Must be accessible for the server
//ini_set('session.use_strict_mode', true); // Uncomment if the id should be renewed, what makes no difference here
echo "Session files before session_start call<br>";
listSessionFiles();
session_start();
echo "Session files after session_start call<br>";
listSessionFiles();
echo "<hr>";
echo "Session id: " . session_id() . "<br>";
echo "Session content: " . print_r($_SESSION, true);
$_SESSION['x'] = time(); // Populate the session with something
function listSessionFiles() {
echo "<ul>";
$none = true;
$dir = dir(ini_get('session.save_path'));
while ($entry = $dir->read()) {
if (preg_match('/^sess_/', $entry)) {
echo "<li>" . $entry . "</li>";
$none = false;
}
}
$dir->close();
if ($none) echo "<li>None</li>";
echo "</ul>";
}
Just reload the page some times. Wait at least more than two seconds. Otherwise the session does not expire.
One way to circumvent the problem is to use cookies with a certain lifetime (below the session lifetime). If the cookie expires it won't be sent to the server. PHP will then create a new session when session_start() is called, so $_SESSION will be empty.
This might be enough to find out that the session is not available. Although one cannot distinguish in PHP if the session has expired or anything went wrong. You can just tell that no session data is available and do appropiate things then (amongst other also destroy the newly created empty session).

Get ID from URL and store it in variable

I need to get the data from URL, example domain.com/?id=username
Username will vary from one user to another... Once they visit the website with link like that, they can move around the website and then at some point fill out the form. Since they moved around the website, the url will not have ?id=username in the path, so I need to store that data in the variable to be able to send it with the form.
I assume I need to set and store the cookie per session (so that cookie will refresh after session / browser exit)
I use ob_start() since I have to implement this code in the body, when the headers are already sent.
ob_start();
session_start();
$affid = $_GET['id'];
setcookie('affid',$affid, 0, "/");
$finalaffID = $_COOKIE['affid'];
ob_end_clean();
echo '<span class="testoutput">'.$finalaffID.'</span>';
After some attempts, I got this code, but it doesnt store the value after I move around couple pages, it only shows the on initial page visit.
Any ideas please?
You could use session variables.
$_SESSION["id"] = $_GET["id"];
this session var will be accessible anywhere the session is open. Just call it with $_SESSION["id"].
index.php
Url: www.domain.com/?id=user
<?php
session_start();
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
?>
otherpage.php
Url: www.domain.com/otherpage.php
<?php
session_start();
if (isset($_SESSION["id"])){
echo $_SESSION["id"];
}
?>
Jose is right about saving IDs in sessions. There's a good post about it that deals SPECIFICALLY with IDs here: Cookie vs Session for Storing IDs
But, if you want to store it as a cookie, this code stores the ID.
$id = $_GET['id']);
setcookie('id', $id);
And this code allows you to retrieve the ID!
echo $_COOKIE['id'];

$_SESSION values do not retain values when passed from another page

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".

undefined variable related to session/cookie

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.

Categories