Increment the Value of a Number in a .txt File with PHP
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.