Archive

Posts Tagged ‘serialize’

PHP Script To Select A Person To Make The Tea

April 6th, 2009 1 comment

In any office there can be arguments about who will make the next round of tea. The following script will allow you to randomly pick a person who is going to make the tea. Rather than have a script that did this once and threw away the information I thought it would be a good idea to use cookies to save the form data for the next time you want to pick a person to make the tea. This is a good exercise if you are trying to understand how cookies work.

First, we will need to variables, the first is an array of people and the second is the number of people in the office.

$people = array();
$number = 10;

We can now build the form that will contain all of our names. Here we just cycle through a simple for loop and if an array item exists in the $people array for the value of $i then we use this in our form.

<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
for ( $i=0 ; $i<$number ; $i++ ) {
    if ( isset($people[$i]) ) {
        echo '<input type="text" name="people[]" value="'.$people[$i].'" /><br />';        
    } else {
        echo '<input type="text" name="people[]" value="" /><br />';    
    }
}
?>
<input type="submit" value="Save &amp; Run" name="submit" />
</form>

Next we need to grab the variables coming from the form and store them in a array, because we used a name with square brackets we can access the people GET variable as if it were an array.

if ( isset($_GET['people']) ) {
  $people = $_GET['people'];
}

We can now select who will be making the tea. Here I use a combination of array_filter() to remove all blank entries in the array and array_rand() to randomly select a key from the array. The array_rand() function returns NULL if it is given a blank array so we need to account for people first visiting the page.

if ( $who = array_rand(array_filter($people)) ) {
    $teaMaker = $people[$who];
    echo '<p>'.$teaMaker.' will be making the tea!</p>';
}

Enabling cookies with this script is quite easy and involves only a small amount of code addition. First we need to create a cookie if the people variable exists. Because this is an array and the setcookie() function requires a string we need to use the serialize() function to convert the $people array into a string value.

if ( isset($_GET['people']) ) {
    $people = $_GET['people'];
    setcookie("teaCookie", serialize($people));
}

Now that we have created our cookie we need to retrieve it again when the page reloads. All cookies are kept by reference in the $_COOKIE superglobal array. Once we are sure that the cookie exists we can user unserialize() to convert our serialized string into an array again.

if ( isset($_COOKIE['teaCookie']) ) {
    $people = unserialize($_COOKIE["teaCookie"]);
}

We now have the $people array in its original state.

Finally, rather than continuously setting and unsetting the cookie I have added a link that will allow you to pick another person from the list, without running the form. We first need to make sure that our cookie exists before allowing this link as it will do nothing.

<?php if ( isset($_COOKIE['teaCookie']) ) { ?>
<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Pick Again!</a></p>
<?php }?>

Of course this script isn’t all that useful if you either don’t drink tea or work alone, but it can easily be adapted to other functions. You can host this script on your Intranet or website for internal usage if you wish, but I have uploaded a version of the tea picker for you to play with, along with the source code.

Serialize And Unserialize With PHP

June 30th, 2008 No comments

If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.

$array = array(1,2,3,4);
$serializedArray = serialize($array);

Now when we print the serialized array out we get the following.

a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;}

This contains all of the data needed to recreate our array. Be careful not to edit this string because it will not work if you want to unserialize it and get the array back. You can store this string in a file or a database so that you can recreate the exact same array at a later date.

If you do chose to store the serialized string in a database you might want to encode it as well. This is to stop the database encoding or removing any characters and destroying your array. To encode the string you can use the base64_encode function in this way.

$encodedSerializedArray = base64_encode(serialize($array));

This string now contains the following.

YTo0OntpOjA7aToxO2k6MTtpOjI7aToyO2k6MztpOjM7aTo0O30=

To get the array back again we use the unserialize() function like this. If you used the base64_encode() to encode the array then you can use the base64_decode() function to turn it back into an unserializable string again.

$array = unserialize($array);

The $array variable now contains our original array.

The same can also be done with objects in exactly the same way. The main difference is that PHP will try to call the __wakeup() function of the object (if it exists) once it has been reconstructed.