Introduction to Serializing

Introduction to SerializingIntroduction

Serializing is a technique that allows you to turn variables, arrays, functions or objects from PHP into a form that can be used to store them, and when needed, convert them back into PHP.

Serializing is useful for flatfile applications that store things in arrays, and are good for CMS features that can let you edit how it works to an advanced degree.

There are two primary functions used in serializing, and they are:

serialize( $your_object_here );

This can be a variable, array, function or object. It turns it into the storable form.

unserialize( $your_string_here );

This must be a serialized PHP string, otherwise it will fail. It turns it back into a data type that is useful to PHP, exactly as it was when you serialize()'d it.

Since it's a very simple function, but sometimes people don't know what to do with it, today we're going to write a very simple example that will do this:

  1. Take data from PHP and serialize it, then store it in a text file.
  2. Open up the serialized file, and then allow you to edit its values.
  3. Save it back into the text file.

It's pretty straightforward, so let's get started...

We're going to set up an array of people and their favourite foods...

<?PHP

$array = array(
"Steve" => "Bacon",
"John" => "Radishes",
"Peter" => "Sandwiches",
"Will" => "Cupcakes",
"David" => "Burgers"
);
?>

Once we've got this set up, we can serialize it:

<?php
print serialize($array);
?>

And, it should look like this:

a:5:{s:5:"Steve";s:5:"Bacon";s:4:"John";s:8:"Radishes";s:5:"Peter";s:10:"Sandwiches";s:4:"Will";s:8:"Cupcakes";s:5:"David";s:7:"Burgers";}

As you can see, it looks somewhat like its PHP equivalent, but full of numbers. I'm not going to go into what the numbers mean, because I don't know, and I can't be bothered, so without further ado, we're now going to save this information into a .txt file. Make a new file called data.txt and CHMOD it to 777.

<?php
$res = fopen("data.txt","r+"); // Opens a resource
$string = serialize($array); // Sets a variable to identify the serialized array
$write = fwrite($res,$string); // Writes it to the file
if($write) {
echo "Data written.";
}
else {
echo "There was a problem.";
}
@fclose($res);
?>

Now that you've done that, we're now going to construct a page that will:

  • Unserialize the data
  • Put it into an HTML form
  • Allow editing
  • Save it back in the text file

<?php
if($_POST[submit]) {
$newarray = array(); // New, blank array.
foreach($_POST as $key => $val) {
if($key!="submit") { // We want to exclude the submit button
(it's part of $_POST)
$newarray[$key] = $val;
}
}
$newarray = serialize($newarray); // Serializes our new array.
$res = fopen("data.txt","r+");
$write = fwrite($res,$newarray);
if($write) { // If it works, which it will...
echo "It worked!";
}
else { // In the unlikely event of the plane crashing...
echo "It didn't work..";
}
}
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" name="data" id="data">
<?php
$data = unserialize(file_get_contents("data.txt")); // Unserializes the file's contents, therefore turning itself into an array.
foreach($data as $key => $val) { // Iterates through the array
echo $key. ' <input type="text" id="'.$key.'" name="'.$key.'" value="'.stripslashes($val).'" />'; // Writes an input box for each key.
}
?>
<input type="submit" id="submit" name="submit" value="Update" />
</form>

And that's it! You can see a working example (and an HTML copy of this tutorial) at www.avengex.com.


Related Articles

  • XHTML vs. HTML
    A quick introduction to XHTML
  • PHP Introduction
    A short and simple introduction to
  • Introduction to Procedural Programming
    Well start of with if
    Here is the basic usage of it
    variable would be something like $variable
  • Introduction to FTP
    FTP stands for File Transfer Protocol and is a standard application protocol that uses the Internet
  • What IS A Blog?
    People maintained blogs long before the term was coined, but the trend gained momentum with the introduction of automated published systems, most notably Blogger at blogger.com...
  • The Beginner's Introduction to SEO
    Here is a question for you: Would you rather have a really artistic and beautifully designed website or an ugly and very plain looking one? Well obviously you would naturally pick the pretty one right? However, here is a second question: Would you rather show up on the first page of major search eng...
  • Introduction to Graphic Design
    If you are going to go into practically any form of business, graphic design is something you are going to become familiar with quickly. Here is a primer.
  • Introduction To Cookies
    Cookies : A collection of information, usually including a username and the current date and time, stored on the local computer of a person using the World Wide Web, used chiefly by websites to identify users who have previously registered or visited the site.
  • Introduction to Induction
    Induction familiarizes the new recruits to the organization functioning so that they become productive in the least possible time; they are a means of honing the workforce to greater efficiency, precision, and perfection.
  • Flash Intros On Websites - Why It's Time To Ditch The Flash Intro
    The designer who wrote this article makes some very good points about Flash Intros. After he explains the pros and cons of Flash Intros he gives great advice in deciding for yourself, with new understanding.

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.