Main
Use SSL

HTTP session handler (php class)

22 April 2008


You know all those times when file_get_contents() just isn't enough? If you want to send cookies with your request, or send it as POST, you'll have to use sockets.

Lately I've been writing lots of php scripts that had to handle HTTP sessions. By "sessions" I mean acting like a web browser. Saving cookies, sending them, following 301/302 redirects, etc.

Eventually I wrote up a class that handles all of that seamlessly. The class itself is new (written a few days ago), so bugs are a very real possibility.

The code is located here: http://own-the.net/code/httpsession.txt

Except for the class httpSession, the code contains 2 other routines. extractSingle() and extractMulti(). The first one returns the first occurrence of a substring that is located between 2 given substrings. The second one returns an array of all such occurrences.These are pretty useful routines, especially if you write a bot or spider. (And yeah, I did hear about REGEX, no need to point this out).

Here is an example of how to use this class:

<?php //Include the httpSession class php file include 'httpsession.php'; //Create an instance of the class $h = new httpSession(); //Allow following 301/302 redirects $h->follow_redirect = true; //Set a cookie named "name", and give it a value $h->setCookie("name", "value"); //Set a referer string $h->referer = "Something"; //Send a request to somesite.com. //(This procedure returns the HTML of the main page, however, we don't use the return value here) $h->httpGet("http://somesite.com"); //Echo a new cookie named "newcookie" that was set by the server. echo $h->getCookie("newcookie"); //Echo the response after sending a POST to the specified URL with the specified data echo $h->httpPost("http://somesite.com/form?id=123", "var=val&something=else"); ?>


This example covers most of the things this class handles, however, it has more features. Feel free to take a look at the code, the class-member names are pretty self explanatory.

Enjoy, and use this wisely.


Posted by: kGen | In category: Php Development | Comments (0)