Rosso Glitterato
Sito in lingua italiana Website in English language
Debug a PHP routine
What is it

This is a PHP function that permits to debug a PHP routine. This function receives in input the variable to debug and create a text file named "myDebug.txt" containing "Variable Name" and "Variable Value"

Function

function myDebug($var){
 
    // File debug name
    $file = "myDebug.txt";      
 
    // Open file debug
 
    if (!(file_exists($file)))
    {fopen($file,"w");}   
 
    // Variable name
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            $variableName = $var_name;
        }
    }
 
    // Debug Var
    $stringDebug = "-------------------------------------------------------------"."\n";
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
    $stringDebug = "Var: ".$variableName."\n";
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
    $stringDebug ="Value: ";  
 
    if (gettype($var) === 'array'){
 
        ob_start();
        var_dump($var);
        $content = ob_get_contents();
        ob_end_clean();
 
        $stringDebug .= "\n".$content."\n";
    }           
    else{
        $stringDebug .= $var."\n";
    }
 
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
 
    // Close Debug
    fclose($txtDebug);
 
}

How to use it

Suppose that in your PHP routine you want to track the variable $a, $b, $c

$a = array("apple", "beer");
$b = "Hello";
$c = 44;
 
myDebug($a);
myDebug($b);
myDebug($c);
 

When you run the routine it will be created the file "myDebug.txt" with this content:

Rosso Glitterato, un sito di Morris C.Rosso Glitterato is a website created by Morris C. - 2018
Website validated W3C for l'HTML5