show_var e log_var

marino51

Utente Attivo
28 Feb 2013
3.203
207
63
Lombardia
lo script che pubblico, ha lo scopo di verificare e mettere a punto ma anche di documentare i contenuti di array e o oggetti

lo script si compone di 2 funzioni, "show_var" e "log_var", che accettano l'elemento da visualizzare e / o registrare nel log
anche in questo caso, interessa il risultato che produce,
non la bellezza del codice o delle sue presentazioni
il risultato è la concretezza, l'estetica è solo una componente soggettiva

può essere usato per qualsiasi tipo di array e/o oggetto per verificare o documentare i suoi contenuti,
si, esistono "var_dump" e "print_r", ma quanta fatica in meno ....

le funzioni si eseguono molto semplicemente, includendo lo script e richiamandole all'interno del proprio codice dove servono

PHP:
$pagina = '{"success":{"msg_user":"","msg_id":"","users":[{"userid":"","card":"00000104","firstname":"Mario","lastname":"Rossi","email":"","birthday":"","phone":"","address":"","city":"","zip_code":"","country":"","privacy_profilazione":"0","privacy_mktg":"0","privacy_regolamento":"0","card_detail":{"status":{"attivazione":"","associazione":"associata"},"coupons_used":0,"coupons_available":0,"points_balance":{"points":0,"grand_total":0,"last_update":"2017-12-10 12:12:59"}},"store_frequency":"0","transactions":"","sesso":""}]}}';
$data = json_decode($pagina);

require_once 'myUtils/show_vars.php';

echo "<h2>pagina</h2><br />".show_var($data);      // visualizzazione sullo schermo

error_log(PHP_EOL."pagina => ".log_var($data), 0); // registrazione nel log

// altri esempi
echo "<h2>Lista di tutte le variabili definite</h2><br />".show_var(get_defined_vars());
echo "<h2>POST</h2><br />".show_var($_POST);

nella "log_var" è stato inserito un limite per gli elementi che dovessero superare i 255 caratteri
(per esempio, 730 precompilato invia e riceve file di lunghezza molto maggiore come elementi di array/oggetti)

PHP:
<?php
function show_var($variable)
{
    $tabella = "<table border='1'>"
             . "<thead><tr><td><b>KEY</b></td><td><b>VALUE</b></td></tr></thead>"
             . "<tbody>";

    foreach ($variable as $key => $value)
    {
        if ($key !== "_SERVER")
        {
            if     ($value == "0")     $value = 0;
            elseif ($value === true)   $value = 'true';
            elseif ($value === false)  $value = 'false';
            elseif ($value === null)   $value = 'null';
            elseif ( empty($value) )   $value = 'empty';

            if ( is_array($value) or is_object($value) )
            {
                $tabella .= "<tr><td>".$key."</td><td>".show_var($value)."</td></tr>";
            }
            else
            {
                $tabella .= "<tr><td>".$key."</td><td>".$value."</td></tr>";
            }
        }
    }
    $tabella .= "</tbody>";
    $tabella .= "</table>";
    return $tabella;
}

ini_set('log_errors_max_len', 8192);

function log_var($value, $max_depth = 99, $key = NULL, $depth = 0, $refChain = array(), $tab = NULL, $text = NULL)
{
    if($depth > 0)  $tab = str_repeat("    ", $depth);

    $text .= $tab . ($key !== NULL ? $key . " => " : "");

    if (is_array($value) || is_object($value))
    {
        $recursion = FALSE;
        if (is_object($value))
        {
            foreach ($refChain as $refVal)
            {
                if ($refVal === $value)
                {
                    $recursion = TRUE;
                    break;
                }
            }
            array_push($refChain, $value);
        }
        $text .= (is_array($value) ? "array" : "object") . "<br />".$tab."( ";

        if ($recursion)
        {
            $text .= "*RECURSION* ";
        }
        elseif (isset($max_depth) && $depth >= $max_depth)
        {
            $text .= "*MAX DEPTH REACHED* ";
        }
        else
        {
            if (!empty($value))
            {
                $text .= "<br />";
                foreach ($value as $child_key => $child_value)
                {
                    $text .= log_var($child_value, $max_depth, (is_array($value) ? "[" : "") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain) . ",<br />";
                }
                $text .= "<br />" . $tab;
            }
        }
        $text .= ")";

        if (is_object($value))
        {
            array_pop($refChain);
        }
    }
    else
    {
        if     ($value == "0")          $value = 0;
        elseif ($value === true)        $value = 'true';
        elseif ($value === false)       $value = 'false';
        elseif ($value === null)        $value = 'null';
        elseif ( empty($value) )        $value = 'empty';
        elseif ( is_string ($value) and strlen($value) > 255 ) $value = 'MAX-LEN';

        $text .= $value;
    }
    $text = str_replace("<br /><br />", "<br />", $text);
    $text = str_replace("<br />", PHP_EOL, $text);

    return $text;
}
?>
upload_2017-12-18_11-12-6.png


upload_2017-12-18_11-13-29.png


salute a tutti e buon Natale
 
Ultima modifica:

marino51

Utente Attivo
28 Feb 2013
3.203
207
63
Lombardia
ho dimenticato, se l'array da verificare fosse in javascript ?
si può inviare (Ajax) l'array ad uno script php che richiama le funzioni del post precedente
HTML:
    var chart = $('#container').highcharts (myChart); // myChart è l'array da controllare

        var myArray = JSON.stringify(myChart);

        alert(myArray);

            $.ajax
            ({
                type:    'post',
                cache:   false,
                url:     'ShowJsArray.php',
                data:
                {
                    data : myArray,
                },
                success: function(response)
                {
                    $('#myDiv').html(response);
                },
                error: function(request, status, error)
                {
                    alert('errore esecuzione ShowJsArray.php '+request.responseText);
                }
            });
ShowJsArray.php
PHP:
<?php
require_once 'myUtils/show_vars.php';

$data = json_decode($_POST['data']);

error_log(PHP_EOL."myChart => ".log_var($data), 0);
echo "<h2>myChart</h2><br />".show_var($data);
?>
 

marino51

Utente Attivo
28 Feb 2013
3.203
207
63
Lombardia
stanco di leggere le fatture elettroniche nel formato xml per controllo,
ho inserito una riga nella funzione show_var, ottenendo la visualizzazione uguale ad un'array
riposto l'intero codice (poche righe) per chi la volesse utilizzare,
PHP:
function show_var($variable)
{
    $tabella = "<table border='1'>"
             . "<thead><tr><td><b>KEY</b></td><td><b>VALUE</b></td></tr></thead>"
             . "<tbody>";

    foreach ($variable as $key => $value)
    {
        if ($key !== "_SERVER")
        {
            if ( is_object($value) and count($value) == 0 ) $value = (string)$value;

            if     ($value == "0")     $value = 0;
            elseif ($value === true)   $value = 'true';
            elseif ($value === false)  $value = 'false';
            elseif ($value === null)   $value = 'null';
            elseif ( empty($value) )   $value = 'empty';

            if ( is_array($value) or is_object($value) )
            {
                $tabella .= "<tr><td>".$key."</td><td>".show_var($value)."</td></tr>";
            }
            else
            {
                $tabella .= "<tr><td>".$key."</td><td>".$value."</td></tr>";
            }
        }
    }
    $tabella .= "</tbody>";
    $tabella .= "</table>";
    return $tabella;
}

segue un esempio d'uso
PHP:
<?php
require_once 'myUtils/show_vars.php';

$xml = simplexml_load_file('XmlParse.xml');

echo "<h3>XmlParse.xml</h3>".show_var( $xml );
?>

ed uno "spizzico" di risultato

upload_2019-3-1_0-53-3.png
 

MarcoGrazia

Utente Attivo
15 Dic 2009
852
20
28
62
Udine
www.stilisticamente.com
C'è un piccolo problema(?), e cioè, dato che Register Globals è disattivato, la variabile _SERVER non ci sarà nell'elenco, a meno che non la si usi esplicitamente.
In ogni caso, puoi mettere un avviso del tipo:
PHP:
echo 'register_globals('; 
    echo ini_get('register_globals'); 
    echo ') '.phpversion()."\n";
per l'utente, in modo che venga avvisato nel caso non veda nulla o nel caso in cui manchino dei valori che ci si aspetta di trovare.
Ovviamente tutti sanno che Register Globals è stato girato a OFF in modo predefinito dalla versione 4.x del PHP e che così deve rimanere.

Fonte: https://www.php.net/manual/en/function.get-defined-vars.php#69337
 
Discussioni simili
Autore Titolo Forum Risposte Data
Z Slide show CSS HTML e CSS 1
B jQuery - hide & show li items jQuery 13
F limit show datatable ajax Ajax 1
Daniele450 [Javascript] Slide show in java script, senza array con nome visibile dell'immagine Javascript 2
filomeni Show Box Supporto Mr.Webmaster 5
G Funzione hide/show button Javascript 5
D [EXCEL] UserForm.Show Error 438 Windows e Software 1
F show() jQuery 1
M Show Hide non funziona su IE jQuery 2
L colums show/hide Javascript 2
S Slide Show Automatico Discussioni Varie 1
S Slide show risultati in php PHP 3
M On clik show div Javascript 0
J Fading Slide Show Javascript 0
J Vite Spiate il reality show interattivo gratuito on line dal 14 ottobre 2009 Presenta il tuo Sito 0
D All the SHOW Presenta il tuo Sito 0
D Visualiazzare Show reel ( da DvD ) in una pagina web Webdesign e Grafica 2
A Form.close & form.show. POCKET PC Programmazione 0
W colori per lo slide show Webdesign e Grafica 12
H creare delle slide-show dai DivX Windows e Software 0
dragoonslair tutorial show directory PHP 5
B Slide show in DHTML Javascript 3
I [Javascript] Leggere "var" da file .js esterno (per google map) Javascript 6
elpirata [PHP][RISOLTO] Errore di tipo Notice: Undefined index - Come risolvere quando si hanno tante var PHP 10
M [Javascript] "Stampare" nel codice Var JS Javascript 5
B [Javascript] Decompilare codice var Javascript 7
ivarello Ordinare dati Var in ordine numerico PHP 9
P Core.start(), init(), var, passaggio di parametri Javascript 0
O APACHE:[error] [client 127.0.0.1] File does not exist: /var/www/favicon.ico PHP 10
C errore Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' MySQL 0
M require('prova.php'), ma non require('http://localhost/prova.php?var=1") PHP 1
Dusy VAR Code Discussioni Varie 3
metalgemini Problema Codifica caratteri con Replace(var,"","") Classic ASP 3
trattorino [Javascript] come capire procedimento log user Javascript 2
A [PHP] Generazione Log modifiche Database PHP 5
bubino8 [PHP] Controllo Log e Modifiche Utenti PHP 5
felino [WordPress] File di log degli errori WordPress 6
H Interpretare e leggere il file log di sfc/scannow. Windows e Software 0
S [PHP] Algoritmo log in e out PHP 2
R [PHP] Software gestione interventi e creazione registro (log) PHP 1
L [WordPress] Problema Javascript nel log del browser WordPress 1
localhost.nicola File log erroe con phpmailer PHP 3
novello88 Joomla su VPS OVH: non funziona nulla ma nessun errore nel log Server Dedicati e VPS 1
P File di log personalizzato PHP 4
L LOG4J in a tomcat webapplication on a server doesn't create log file Web Server 0
Licantropo Log delle operazioni sul server Apache 0
L Form di registrazione e log in. PHP 2
I log di un router Reti LAN e Wireless 6
T [Microsoft SQL Server 2008 (SP3)] log delle transazioni è pieno Database 1
Trapano like e log PHP 5

Discussioni simili