Increment the Value of a Number in a .txt File with PHP

This post is old. It may contain broken links, missing images and incorrect information.

I was recently asked to amend a simple online ordering system I’d produced for a customer some time ago.

Amongst the updates was a reques to add a simple order number to each order confirmation email as it was sent out. Normally this would be an order ID, or another automatically incremented value stored in a database. However, this system doesn’t store the order details, it simply emails them to the recipients.

So I looked for a different solution and in the end opted to store the value in a plain text value, read it and increment it before storing the new value in the same file.

Here’s my code:

<?php
$file = 'ordernumber.txt'; // the name of the text file (must be writeable by the server)
$orderNumber = file_get_contents ($file); // read file data and store as variable
$fdata = intval($orderNumber)+1; // increment the value
file_put_contents($file, $fdata); // write the new value back to file
?>

This is a simple script, but it solved a problem and prevented me having to make database requests for little reason.

Enjoy!

Jack Barber, freelance web developer based in Whitby, UK

Written By

I'm a freelance web developer based in Whitby, UK. I built my first website using GeoCities, and learned to write HTML and CSS using Notepad. Web technology has come a long way since then, as have my web development skills!

These days I love helping my clients make the most of the internet. I provide design, development, marketing and IT support services, forming long-term partnerships with my clients.

Connect With Me

Posted in Uncategorized