Monitoring errors in php

After developing a system, the next thing that’s supposed to be done is testing it in the real world to make sure that it doesn’t have any problems. Good thing php shows errors whenever they occur on the script that you have written. But its not really good to show errors on a production environment that’s why we need to hide them and make use of the php error log to log the errors occurring in the system as the users are testing it.

Requirements

  • Wampserver / XAMPP
  • jQuery

 

Configuring php.ini

Lets start by configuring the php.ini file so that php won’t display any errors to the users. To do that, just left click on the Wampserver tray icon, select php, then php.ini. Open the file using a text-editor.
Then search for the string below:

display_errors = On

By default, it is set to On. Set it Off by changing the value to Off:

display_errors = Off

Next, search for error_log which has a path assigned to it. It may look like the one below:

error_log = "D:/wamp/logs/php_error.log"

Just change it to match the installation directory of wampserver in your computer. Then press ctrl+s on your keyboard to save the file.

Then click on restart all services from the wampserver tray icon. This is to make sure that the settings will take effect.

 

Monitoring errors

Now all we have to do is to write a script which will read the error log file and display the contents in the browser. Name it error_reader.php.

<script src="jq.js"></script> //import jquery file
<script>
$(function(){
	setInterval(logfile, 1500); //calls the logfile() function every 1500ms

	function logfile(){
		$('#errors').load('read_file.php'); //dynamically load the contents of read_file.php
	}
});
</script>
<div id="errors"></div> //this is where the contents of the error log are being displayed

Then create a new file and name it read_file.php.

<?php
//reads text file
$file = "D:\wamp\logs\php_error.log"; //path + filename of the php error log file
if(filesize($file) > 0){  //checks filesize; nothing is executed if filesize = 0
$handle = fopen($file , 'r');  //open a file
$data = fread($handle, filesize($file));  //reads a file
fclose($handle); //closes the file
?>
<pre> <!--preformatted text: text will be displayed in the same way as it appears on a text-editor-->
<?php echo $data; ?> <!--output file contents -->
</pre>
<?php } ?>

That’s it, open error_reader.php and start monitoring errors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s