Storing Data Using Files in PHP – Shopping Cart

Hi! After adding some functionality to our shopping cart, I am going to do something different today: storage. Assuming we want to collect all the orders from customers and store them in a file somewhere for later use, we can easily create a file and write and read to and from it. I have altered the original look of our simple cart by adding a new input area for shipping address: Let us look at it now.

snapshot1

Adding that single input area is obviously not a big deal but if you have done any online shopping before, there is a good chance you were prompted to enter your shipping address! Now let us take a quick look at the results of submitting your order!

snapshot2

Simple enough, the Address information is now included in the summary! Everything looks great. Now, we both know that just displaying the summary of orders might not be the best way to get the job done – assuming you have a million orders or something. So, to solve this problem, we need to save the orders in a file. We can then retrieve the orders and process them before fulfilling them. So, using a new file, vieworders.php here is what I have done already:

snapshot3

Now we are not worried about anything getting lost because we can look into our file and fetch the orders. That is good. I know you might be asking, but is that the best way to do this kind of job? The answer is NO. Using plain text files is not the most efficient way and the reason why am using it here is to demonstrate why we will need to use a database management system for anything important! Let us look at how to write data into a file.

[php]

#from within store.php we add some new lines of code here
#writing data into files stored in my machine

<? php
$fp = ”;
//create a folder in your directory (orders)
$fp = fopen(“C:ordersorders.txt”, ‘ab’);
flock($fp, LOCK_EX) #lock the file – file cannot be shared
if(!$fp){
echo “<p><strong>Your order could not be completed at this time.”
.”Please try again later</strong></p></body></html>”;
exit;
}
else{
//that means there is no error and we therefore
//can write to a file

$outputstring = $date.” t”. $tiresqty.” tires t”. $oilqty.” oilt”
.$sparksqty.” spark plugst$”.$totalamount
.”t”. $address.”<br />”;

fwrite($fp, $outputstring); //write data to file
flock($fp, LOCK_UN); //release existing lock
fclose($fp); //close the file!
}
?>
[/php]

That is all you need to write to a file. So what did we do here? A few things: first, create a variable $fp (file pointer) and then use PHP’s file open function (fopen()) which takes several parameters. First, the file path and then others. As you can see, I added ‘ab’ as the second param (a – (writing only) for appending to the end of existing content if any. If the file doesn’t exist, try to create it. b – (binary) differentiates between binary and text files – recommended for portability.

I then applied a lock to the file to disable sharing it. I then check to see if the file pointer exists, if not, then inform the customers politely that their order was not processed. Otherwise, go ahead and write their order to our file using fwrite() function. Then remove the lock and finally close the file.

Let us finally take a look at our vieworders.php file which we use to read data from our file as we process them in our parents’ garage!

[php]
<?php
$fp = fopen(“C:ordersorders.txt”, ‘rb’);
?>

<html>
<head>
<title>Crazy Auto Orders</title>
<link rel=”stylesheet” type=”text/css” href=”index.css” />
</head>
<body>
<div class=”container”>
<h1>Crazy Auto Store Inc </h1>
<h2>Customer Orders: </h2>
<?php
if(!$fp){
echo ‘<p><strong>No orders pending.’
.’Please try again later</strong></p>’;
exit;
}
flock($fp, LOCK_SH);
while (!feof($fp)){
$order = fgets($fp, 999);
echo $order. “<br />”;
}
flock($fp, LOCK_UN);
fclose($fp);
?>
<p>Copyright 2013 &copy; Crazy Auto Store Inc </P>
</div>
</body>
</html>
[/php]

Description:

Once again, on top of our file we create a file pointer variable $fp and use file open function fopen() passing in the path and a second param (‘rb’ – r (opens the file for reading from the beginning) and b – for binary differentiation – recommended by PHP developers!).

Just like before, we check to see if the pointer exists and if not, give the user a friendly message to try again later. If it exists, we use LOCK_SH to enable reading lock. The file can be shared with other readers. Using a while loop, we check to make sure that we have not reached the end of the file (feof – file end of file) and output the data one line at a time using fgets() function.

Last but not least, we release the lock and lastly close the file. That is all.

There are so many reasons why this is not the best approach and that is why database management systems were created. I will briefly mention a few:  The speed is affected if our files grow and so reading the data becomes a big challenge. Secondly, searching for a particular group of records is difficult. Another one could be a situation where more than one user is trying to access our file at once – concurrent access. This can become problematic even while using locking. It is hard to enforce different levels of access to data. Those are just a few and if you are interested in finding out more, I would recommend checking out the php documentations .

NOTE: This example does not include everything that file writing and reading entails. With that being said, there are a lot of information online on how to read and write files (functions and such) – this is just a small piece of it. I just touched on the tip of the iceberg here.

If you have any questions, spotted any errors or comments, please leave them below this post using the comments section. Thank you for stopping by and I hope you enjoyed building this shopping cart with me. See you soon!

Be The First To Get New Posts From Simple Developer…

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

Leave a Reply

Your email address will not be published. Required fields are marked *