Friday, May 17, 2013

testing if an http client support cookies via php

Cookies! Such a fundamental part of sessions on the web!

If you're making a little client for http things, like on a mobile device, and you're like me, then you might want to run a test to make sure the system you're using is properly configured to use cookies.

http://nik.chankov.net/2010/01/16/detecting-if-the-cookies-are-enabled-with-php/ is a start, but the example program both 1. assumes it's called "info.php" at the root of the site, 2. requires the client to follow location changes in the header style redirects and 3. you probably still might need a server to put it on.

So I made http://kirk.is/tools/testcookies/redirect.php -- its content is
<?php
setcookie('test', 1, time()+3600);

if(!isset($_GET['cookies'])){
    header('Location:redirect.php?cookies=true');
}

if(count($_COOKIE) > 0){
    echo "YES";
} else {
    echo "NO";
}
?>
If your client has cookies enabled AND can follow the redirect, it will return YES, or else NO.

But the redirection following is kind of an arbitrary requirement, so I have also made http://kirk.is/tools/testcookies/set.php to set a cookie:
<?php
setcookie('foo', 'bar', time()+(86400*7));
?>SET COOKIE
 and http://kirk.is/tools/testcookies/get.php to return YES or NO if it could read that cookie:
<?php
if($_COOKIE['foo'] == 'bar'){
echo "YES";
} else {
echo "NO (".$_COOKIE['foo'].")";
}
?>

Please note that results are best the first time you run it, subsequent runs may be letting you see old cookies. (Hmm, maybe I should expire the cookies once they're read?)

Anyway, I used curl to test this, and learned the default settings of curl don't support cookies or redirection, so I was getting a lot of false negative results.

The line I ended up with is
curl -L -b cookies.txt -c cookies.txt http://kirk.is/tools/testcookies/FILENAME.PHP

The -L follows any location changes, the -b lets it use an old cookie file (i.e. a text file on the local system it will store the cookies in) and -c writes out the cookies that occured in that session. Those are 3 things a typical browser is always doing, and a small http client might or might not do.

No comments:

Post a Comment