Tuesday, 2 December 2008

Using Session to Store Temporary Data

Sessions are a useful way to store temporary data, and even login information. In order to use sessions, the line session_start(); must be on the top of every PHP page you want sessions on.

You can create a new session and initialize it using $_SESSION['some_key'] = 'some_value';. You can retrieve the value of the session in a similar way: echo $_SESSION['some_key'];.

A useful way of using Sessions is to see if a user has logged in (if you don't use cookies). After the user logs in, you can set the session using the above code. Later on, if you want to see if the user has logged in, you can do something like:
if ( isset( $_SESSION['user'] ) ) {
// session exists
// now check if session is valid
} else {
// ask user to login
}

Sessions are stored on the server and are destroyed when the user closes their browser. Sessions can also be destroyed manually, i.e. when the user logs out. You can destroy a session by calling session_destroy();, or a particular session value using unset( $_SESSION['some_key'] );. Destroying a session deletes all session data - so only destroy it if you don't need any of the temporary data.

Labels: , ,

Tuesday, 11 November 2008

Quick and easy way to make a RSS Reader

The quickest way to build a custom RSS reader in PHP is to use the Simple XML library. The library comes with the standard PHP installation but requires you to compile PHP with the extension enabled. More information about Simple XML can be found here.

Here is some simple code to use:
// define feed url
$feed_url = "http://www.xtremeps3.com/rss.php";

// read in xml file
$data = file_get_contents( $feed_url );

// convert xml to objects
$data_array = simplexml_load_string( $data );

// spit out objects
echo '<pre>'.print_r( $data_array, true ).'</pre>';

You can easily put this code into a function to load a user defined RSS feed. To access the elements in the object, you can use $data_array->channel->item->title, for example, to access the title of the first entry in the feed.

The ideal way would be to loop through the $data_array->channel->item object using a foreach loop and output the data you need.

Labels: , , ,