Wednesday, July 10, 2013

PHP debugging with JavaScript Console, Error and Access Log

You can use JavaScript console to output global and other variables from your PHP file. That way you can use JS console to track what is is going on in PHP backed files that are called by $.ajax. Also you should be familiar with PHP's functions utf8_encode and utf8_decode

Raw outuput of JSON string and Base64 encoded JSON string



Here is the source code for index.html:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script>
            function go() {
                $.ajax({
                    type : "GET",
                    url : "job.php?p=" + $('#unittype').val(),
                    success : function(data) {
                        $('#m').html(data);
                    }
                })
            }
        </script>
    </head>
    <body>
        <select id="unittype" name="unittype" onchange="go();">
            <option value="Miner"> Miner </option>
            <option value="Puffer"> Puffer </option>
            <option value="Snipey" selected> Snipey </option>
            <option value="Max"> Max </option>
            <option value="Firebot"> Firebot </option>
        </select>
        <div id="m">
            &nbsp;
        </div>
    </body>
</html> 


and for PHP backend file:job.php

<?php
session_start();
if (isset($_SESSION['visits'])) {
    $_SESSION['visits']++;
} else {
    $_SESSION['visits']=0;
}
echo "Im form AJAX call at ".date('H:i:s');?>

<?php
$_SESSION['city'] = 'Paris';
$_SESSION['country'] = 'France';


$jsonFormatedString = json_encode($_SESSION);
$jb64 = base64_encode($jsonFormatedString);
$jsonFormatedString = str_replace(array('"',"'"),array('”',"’"), $jsonFormatedString);

echo <<<EOT
<script>console.debug("$jsonFormatedString");</script>
EOT;

echo <<<EOT
<script>console.debug("$jb64");</script>
EOT;
?>

Working with apache error and access logs in real time

Must be logged in as root

# cd /etc/httpd/logs
# ls -all
total 1128
drwx------.  2 root root   4096 Feb 14 02:35 .
drwxr-xr-x. 11 root root   4096 Apr  1 21:09 ..
-rw-r--r--.  1 root root 867866 Apr  2 01:10 access_log
-rw-r--r--.  1 root root 269285 Apr  2 01:10 error_log

Shows all rows
shows only rows that have 'select' word and highlights rows until grep reaches ';'
shows rows not containing 101

# tail -f error_log 
# tail -f error_log | grep -i --color "select.*;"  
# tail -f -v error_log | grep -v '101'  

shows rows not containing css, js and images

# tail -f access_log | grep -v 'css\|js\|images'

Sending errors and messages to apache log

// Full file path in error log
error_log( "Error in file ".__FILE__." something went wrong");

// Only file name in error log
error_log( "Error in file  {$_SERVER['PHP_SELF']}" );

Another way to show debug output in console very useful in MVC frameworks

<?php
$_SESSION['city'] = 'Paris';
$_SESSION['country'] = 'France';
$d = addslashes(dirname(__FILE__)).$_SERVER['SCRIPT_NAME'];
echo "<script>console.log(' message in $d ".json_encode($_SESSION)." ');</script>";
?>

Third way that handles strings, JSON and MySQL query strings


This way you can get a console output with Object notation


<?php 
$_SESSION['city'] = 'Paris';
$_SESSION['country'] = 'France';

echo "<script>console.info('".$_SESSION['city']."');</script>\n";
echo "<script>console.info(".json_encode($_SESSION).");</script>\n";

$jsonString = '{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}';
echo "<script>console.info($jsonString);</script>\n";

$query = "SELECT * FROM `table` WHERE `name` = 'Mark'";
echo "<script>console.info(\" $query \");</script>\n";
?>

No comments:

Post a Comment