Are Javascript/Cookies enabled or disabled? - php

I am looking for some code that will return me values if the user has JavaScript enabled or disabled, as well as cookies.
I know this is probably easy to do, but my time constraints are so tight, it hurts. There has to be something out there using php that does this. Ideally I would love to find code that has a page setup with all the possible values that could affect my scripts.
EDIT: Obviously JavaScript may be disabled, but, I am hoping that I can find something out there to test the two cases.
My Solution
For anoyone else looking for code to detect if the users has cookie enabled or disabled, here is what I ended up coming up with from the posts below... you can just drop this at teh top of any page and it works...
<?php
// do a cookie test
if (!isset($_SESSION['cookie_check']))
{
if (!isset($_GET['cc']))
{
// drop a cookie in their bag
setcookie("cookiecheck", "ok", time()+3600);
header("Location: ".$common->selfURL()."?cc=1");
exit(0);
}
else
{
// do we have a problem?
if (#$_COOKIE['cookiecheck'] != "ok")
{
// we have a problem
header("Location: /site-diag.php");
exit(0);
}
else
{
$_SESSION['cookie_check'] = true;
}
}
}
?>

You could use the jQuery cookie plugin to write a cookie and then see if you can read it back again. That would tell you if cookies were enabled in the client's browser or not.

For checking Javascript, either they have it or they don't. If not, you can use <noscript> tags to display a message asking them to turn it on, put a meta redirect inside, etc. That is the extent of your testing ability.
As for cookies, just try setting a cookie then reading it back! Since you're concerned about Javascript's ability to handle cookies, I assume you already have a cookie library that you are using, meaning that you can just use the set function for a test cookie then the get function to read it back. If the test cookie can't be read back, cookies are off.

Here is one for checking cookies
http://techpatterns.com/downloads/javascript_check_cookies.php

if javascript is disabled then you can't use jquery or prototype.
write a function that writes a cookie, then tries to read it.
and secondly puts out some js code to the screen that makes a ajax call to a basic php script.
you can use a database to set the boolean results of both tests on the visitor table if there is one.

This is the way I check if cookies and JavaScript are enabled:
if($_SESSION['JSexe']) { // 3rd check js
if($_COOKIE['JS']) {
setcookie('JS','JS',time()-1); // check on every page load
}
else {
header('Location: js.html');
}
}
// 2nd so far it's been server-side scripting. Client-side scripting must be executed once to set second cookie.
// Without JSexe, user with cookies and js enabled would be sent to js.html the first page load.
elseif($_COOKIE['PHP']) {
$_SESSION['JSexe'] = true;
}
else { //1st check cookies
if($_GET['cookie']) {
header('Location: cookies.html');
}
else{
setcookie('PHP','PHP');
header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1');
}
}
Explained in detail here: http://asdlog.com/Check_if_cookies_and_javascript_are_enable

First, realize that you can't use JavaScript to check for cookies if JavaScript is turned off. The usual check for cookies being on is to write one and then read it.
Do you care about the case when cookies are on but JavaScript is off? What are you going to do based on the information?
I found this code here for checking for a cookie via PHP. Doesn't rely on JavaScript. Is PHP your server language?
<?php
class cookieCheck
{
public function check()
{
if (setcookie("test", "test", time() + 100))
{
//COOKIE IS SET
if (isset ($_COOKIE['test']))
{
return "Cookies are enabled on your browser";
}
else
{
return "Cookies are <b>NOT</b> enabled on your browser";
}
}
}
}
?>

Related

PHP detect if session cookies are disabled

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.

Session variable not being saved from $_REQUEST

I think i'm missing something obvious. I have a session started at the very top of my page. Below that i have the following code. The var dump out puts "one" when it is displayed from the requested page. After refresh the var dump out puts NULL. Why is this not getting saved?
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
If you have session_start() at the top of your page, as you claim, then your code should look something like this:
session_start();
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
This should 100% work, no question. There IS something else stopping this from working in your code that you have not supplied. My first guess would be a session destroy of some kind.
First, you need to ensure you start the session before attempting to use it. Secondly, it is recommended that you specify either POST or GET instead of generally using REQUEST. If you want to support either GET or POST, you might do something like this:
// Begin Session Management
session_start();
// Check both GET and POST for the parameter
if($_GET['page'] == 1 || $_POST['page'] ) {
// Modify the session
$_SESSION["one"] = true;
}
// See what we ended up with in the session.
var_dump($_SESSION["one"]);
This works for me, but I'm using memcache as my session session handler. Verify your own session handler in php.ini, and ensure that the session handler is working properly. Also, ensure you are closing the session properly if you are redirecting, setting a new location, or exiting in unusual ways.

Check if session has been started and set global var for javascript to use

I have the following setup:
index.php
subpage.php
When visiting either pages I have a "header intro animation". I only want the user to see this animation upon first page visit and not repeat it when refreshing/visiting other subpages within the same session.
I've tried doing the following:
$disableAnimationOnOtherPages;
if(session_id() === '')
{
// session has NOT been started
session_start();
echo "SESSION WAS NOT SET";
}
else
{
// session has been started
echo "SESSION HAS BEEN SET";
$disableAnimationOnOtherPages = true;
}
So when I visit any page the first time I set/start the session and then if I refresh or go to a subpage, then $disableAnimationOnOtherPages = true; will be set, so that I can use it as a reference to disable my javascript animation in my included .js file further down.
But regardless of what I do, im only getting "SESSION WAS NOT STARTED".
Any ideas on what im doing wrong in this context?
session_start(); doesn't mean 'create new session', it means create or continue the previously started session, you can then use $_SESSION to store values in.
So what you really want to do is:
session_start();
if(!isset($_SESSION['disableAnimation']))
{
// Session wasn't started, show animations.
$_SESSION['disableAnimation'] = false;
}
else
{
// Session has been started previously, disable animations.
$_SESSION['disableAnimation'] = true;
}
You can then use $_SESSION['disableAnimation'] to disable your animations instead of a global variable, as globals are generally frowned upon.
Edit:
To the access this in JavaScript, you would need something like:
<script type="text/javascript">
var disableAnimation = <?=$_SESSION['disableAnimation'];?>;
// do Javascript stuff with disableAnimation
</script>
try removing the $disableAnimationOnOtherPages that is at the top of the script? I've had similar issues where it only activates the first instance and it seems to be an issue with the order that a function is called.
OR (I've done this lately too)
Have the first conditional be the exception?
if(session_id !='')
{
//session has been started
echo "SESSION HAS BEEN SET";
$disableAnimationOnOtherPages = true;
} else {
//session has NOT been started
echo "SESSION HAS NOT BEEN SET";
session_start();
}
this is totally untested, just a top of my head idea to try. (I've been up against similar issues and have been playing around with both of these ideas, sometimes they work and other times the code laughs at me yelling "SUCKER")

Test for cookies in PHP

What is the best way to tell if someone has cookies enabled in their browser. I tried:
<?php
setcookie('cookies','yes',time()+7200);
if (!isset($_COOKIE['cookies'])) {
echo '<div class="error" style="float:right;">You must enable cookies and Javascript to use this site.</div>';
} else {
echo '';
}
?>
but sometimes it displays the alert even if cookies are enabled. I only want an alert if cookies are NOT enabled.
The reason that your code doesn't work is because cookies are sent with the request. The code you're trying will work, but setcookie has to be in a different request than the isset call. Try calling a redirect in between calling those 2 functions.
It is because your cookies are set at the same time as your request is sent to the browser.
It means that even if setcookie() is executed before the script ends the cookies are set after the browser received the request.
To do in a such way, you would need to redirect to a page with a trivial argument and then check for cookies.
A more flexible solution would be to check in javascript.

Whats wrong with this php code, keep getting Error no 2?

<?php
session_start();
// After user logged in
session_regenerate_id();
$_SESSION['logged_in'] = 1;
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT'];
// Session Checking
function session_check(){
if(isset($_SESSION['logged_in']) && !empty($_SESSION['logged_in'])){
if(isset($_SESSION['ip']) && !empty($_SESSION['ip']) && ($_SESSION['ip'] == $_SERVER['REMOTE_ADDR'])){
if(isset($_SESSION['agent']) && !empty($_SESSION['agent']) && ($_SESSION['agent'] == $_SERVER['HTTP_USER_AGENT'])){
return true;
} else {
echo "Not allowed to view this page. Error no: 3. You will be redrected to login page in few seconds";
header('Refresh: 3; url=./login.php');
}
} else {
echo "Not allowed to view this page. Error no: 2. You will be redirected to login page in few seconds";
header('Refresh: 3; url=./login.php');
}
} else {
echo "You are not allowed to view this page. Error no: 1. You will be redirected to login page in few seconds";
header('Refresh: 3; url=./login.php');
return false;
}
}
And I keep getting error no2 when I run:
if(session_check()){ echo "something";}
Is it because I am using dynamic IP?
Is my code good enough to protect session hijacking?
If I exclude the ($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']), it works perfectly.
Important Question:
What are your anti session hijacking methods? Can share with us? Using IP-checking, user-agent checking or probably other methods??
Yes, a dynamic IP address would cause you to get logged out as a user of this code as soon as your IP address changes. You shouldn't be using the IP address to check for session security. The user agent check you already have should be enough on its own.
Here is a great article on session security: http://phpsec.org/projects/guide/4.html. Near the bottom it shows how you can make the user agent check even more secure using md5 hashing. Also here is an excerpt concerning IP addresses:
It is unwise to rely on anything at the TCP/IP level, such as IP address, because these are lower level protocols that are not intended to accommodate activities taking place at the HTTP level. A single user can potentially have a different IP address for each request, and multiple users can potentially have the same IP address.
I'm assuming there is more happening between the setting of the variables and the checking. That is probably what is causing the problem, but it is difficult for us to say what could be causing it when we don't see any error messages or any code that might be causing it. Try echoing out what session[ip] actually is and post it here.
You cannot echo anything before issuing a write to header unless you use output buffering. I suggest you return a status code instead, instead of putting the header inside the session_check function. After all, it is named session_check, not session_check_redirect() :D
From the PHP manual on header()
Remember that header() must be called
before any actual output is sent,
either by normal HTML tags, blank
lines in a file, or from PHP. It is a
very common error to read code with
include(), or require(), functions, or
another file access function, and have
spaces or empty lines that are output
before header() is called. The same
problem exists when using a single
PHP/HTML file.
I don't see what's wrong with your code. As suggested, try var_dumping the content of both $_SERVER and $_SESSION at the beginning of session_check() to see what they contain.
Even if you use a dynamic IP, it should not change between two requests (it usually changes when you unplug your network cable or disconnect your wifi card).
Your method may help against session hijacking, but would not work when the attacker is behind the same public IP address as the user.
I suggest reading OWASP recommendations for best practice in web security.
A agree with Marius, there's probably more going on.
I've taken the liberty of making your if..else logic more readable:
function session_check(){
if (empty($_SESSION['logged_in'])){
echo "Error no: 1.";
return false;
}
if (empty($_SESSION['ip']) || ($_SESSION['ip'] != $_SERVER['REMOTE_ADDR'])){
echo "Error no: 2.";
return false;
}
if (empty($_SESSION['agent']) || ($_SESSION['agent'] != $_SERVER['HTTP_USER_AGENT'])){
echo "Error no: 3.";
return false;
}
return true;
}

Categories