PHP detect if session cookies are disabled - php

I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?

You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else

assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page

If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.

Related

How to check if a session is expired or never was set in php

How can I check if a session was ever set or was set but expired?
I am using this code and I want to make an echo if the session has expired like this: Session has expired. Please login again
This is my code:
session_start();
if(!isset($_SESSION['sfmlogin'])){
?>
Login again
<?php
exit();
}
So for users who visit the page for the first time, they should not get an echo likesession expired because they did never login before.
The information you are looking for is in the session meta-data - but this is not exposed via the API. The default handler uses files - so if the file exists, then there was a session. but you should not attempt to bypass the handler to get session metadata! That would be a very bad idea. Really, it sounds like you should be writing your own session handler which also exposes the metadata.
Session has expired
This is a very complicated proposition: with the default handler (leaving aside the problem of bypassing the handler to get the meta-data) there is no session expiration - there is only garbage collection of session data which hasn't been touched for some time. On some systems this is handled by a batch process. On some it is a stochastic event. So in effect, and in this context, there is no difference between an expired session and no session from the server's point of view.
You could infer from the cookies if the browser thinks it should have a session:
session_start();
if ($_COOKIE(session_name() && !count($_SESSION)) {
print "session has expired";
exit;
} elsif (!$_COOKIE(session_name()) {
print "You need to login first";
exit;
} else {
print "welcome back....";
....
...but do make sure that you put something in the session when the user logs in.
How about doing a boolean check on session_status()? If it returns true, then the session is active, else, it would return a "Session Expired" notice. http://php.net/manual/en/function.session-status.php
Edit: You would only need to check session_status() after a user has logged in. If they have not, then the session has not been started, therefore $_SESSION would already be false and a session expiration notice wouldn't be possible.

Just how safe is protecting a page with session_start()?

After my login page all my other pages are inaccessible unless you are logged in. And basically to check if you are logged in I have a simple if else statement:
session_start();
if (isset($_SESSION['id'])) {
// Show the page
} else {
// Ask the user to log in
}
And for the admin pages I have an extra check:
session_start();
if (isset($_SESSION['id']) && $_SESSION['isAdmin'] == TRUE){
// Show the page
} else {
// Unauthorised access
}
Is this a safe way of protecting PHP pages?
Yes it is the safe way. and try to add <?php if(!session_id()) session_start(); ?> at the top of the page because if you have included this page in another page and session is already started in that page, the session will be canceled and this page will be prone to unauthorized users.
It depends.
All PHP session variables are stored on the server side. The moment a session is started by session_start();. PHP sets a temporary cookie on your computer named PHPSESSID set to expire at the end of the browsing session. Using this cookie PHP server assigns values to the session variables. Whenever you log out (i.e, session_destroy();), this PHPSESSID cookie value is made useless
The insecure bit about this is if someone actually stole your PHPSESSID cookie value, the person can simply set this PHPSESSID cookie on their computer and have access to your session without even entering any username or password. However this can be mitigated if you use SSL/HTTPS on your web server. It must be enforced wherever session_start(); is used. You must force SSL/HTTPS where sessions are used. If you just use SSL/HTTPS for login, and HTTP for the rest of the session, this doesn't make you safe as the PHPSESSID cookie is sent in plaintext via HTTP.
As far as I know the only way to compromise PHP's Session mechanism is to steal the PHPSESSID cookie using man-in-the-middle attacks, which can be totally made useless if you have a valid SSL certificate and use of strong cipher suite for your webserver. This cookie can also be retrieved using properly crafted XSS attacks, which can be mitigated if you filter javascript or equivalent from the PHP input to your PHP code using preg_replace with the proper regex.
create one function then call this function when you load your page.. this function return true and false if you login or not and then you can manage your URL redirection..
oR
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
this lucks good..

How to determine cookie validity?

I am starting the session as
session_start(); //So This session will get destroyed when user exit the browser
I set the cookie as
setcookie('cookie',$value,time()+3*60);
$_SESSION['cookie'] = true; //When user log in, I don't need to get the
salt again from db and do all the security
checks. Assume it as a cache
This suggesion is suggested in this question.
The problem is, cookie gets expired after 3 minutes. But session exists. So user tries to login after 3 minutes
if($_SESSION['cookie'])
{
//success
}
else
{
//Authenticate user
}
But this is wrong. Since cookie expired, else part should execute. But if part gets executed. I understand that session is still alive. How do I handle this situation?
I understand that it is due to that time()+3*60. But how do I implement that cache thing?
You need check cookie not in $_SESSION.
Check them in $_COOKIE.
As example:
if($_COOKIE['cookie'])
{
//success
}
else
{
//Authenticate user
}
Cookies and session variables are not related (except that PHP internally uses a cookie named PHPSESSID to connect the client to its session). Expiring the cookie doesn't have any effect on a session variable with the same name. If you want to test whether the cookie has expired, use:
if (isset($_COOKIE['cookie']))

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

How to (if possible) set and unset session variables/ stop session cookie overwriting?

For background, here's my scenario:
I'm building a self-hosted platform for a particular niche, and part of that platform is the login process, which if validated sets a session for the user. On every administration page load, the session is started and the variable $_SESSION['key'] checked to see if it's true.
If it's false, the user is re-directed to the login page with an error telling them to login again.
The problem is this is dependant on a session cookie being set or not set, in the sense that when the session cookie expires and the session is started with session_start() to check $_SESSION['key'], therefore creating a new session cookie with default values (I use session_set_cookie_params() to alter the path, timeout etc) making it impossible to re-login as session cookies do not overwrite from what I can see.
In order to fix this I've thought about using something like session_set_cookie_params(5, ..) before session_start() when checking $_SESSION['key'], which will create a 5 second session cookie, therefore allowing a new one to be created when re-logging in, but I'm not sure whether this would work - and I'm also sure there must be a more efficient way to set/unset a session variable?
Here's my code:
Start session if validated login
if($validated){
session_set_cookie_params(1800, "/inst", $server_name['home']);
session_name("_inst");
session_start();
$_SESSION['key'] = true;
}
Check if $_SESSION['key'] is still true
session_name("_inst");
session_start();
if(!$_SESSION['key']) {
header('Location: ' . $server['home'] . '/login/?error=1');
}
Any answers or advice would be great, and please do ask if you need clarification on anything!
Just issue a session_start() on all pages. This'll unconditionally create a session for you, then you can check for the presence/abscence of the key:
<?php
session_start();
if (!isset($_SESSSION['key'])) { // never logged in, or were logged in and got logged out
... redirect to login ...
exit();
}
if ($_SESSION['key'] != 'expected value') { // logged in, but no longer a valid login.
... redirect to login ...
exit();
}
You shouldn't have to mess with the session cookie settings at all. Leave them at default and simply check for the relevant key(s). if they're not there, then the user is not logged in and should be redirected.
If their session had expired and PHP cleaned up the session file, then they've been effectively logged out, even though they have a it-was-valid-at-one-point-in-time session key, and should get redirected to login again.

Categories