Create your own log file with php add text to a new line

March 28, 2009

I created this the other day for one my websites and find it very handy. For instance if you want to creat your very own log file of all your php and mysql errors youll have a nice convenient text file which contains all of your logs.
You can even take it that little bit further and create access logs or logs for particuarly actions etc. Its simple enough to code so just follow the steps below.

  1. Create a file called logfile.txt on your server (make sure you remember the path to that file).
  2. Insert the below functions either directly into your page, or into your functions page.

[sourcecode=php]//File will be rewritten if already exists
function append_file($filename,$newdata) {

3. Then all thats left is to just call that function like so below, a new line of text will be added to the bottom of the new logfile.txt file.

[sourcecode=php] //add more data ot the existing file
append_file("../logs/logfile.txt","New text addedn");[/sourcecode]

You can take this further if you wish and add a read file module.

  1. You can simply do that by adding the below function to your page.

function read_file($filename) {
return $data;

  1. Once again you can use this function by simply calling in on your page.

echo "Data in file : <b>$data</b>";

I hope this might be useful to someone else.

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.