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.


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!


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:


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.


#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
echo “<p><strong>Your order could not be completed at this time.”
.”Please try again later</strong></p></body></html>”;
//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!

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!

$fp = fopen(“C:ordersorders.txt”, ‘rb’);

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


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!

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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.