¿Cómo puedo escribir en la consola en PHP?


¿Es posible escribir cadena o iniciar sesión en la consola?

Lo que quiero decir

Al igual que en jsp, si imprimimos algo como system.out.println("some") estará allí en la consola, no en la página.

Author: Bhargav Rao, 2010-12-01

23 answers

Firefox

En Firefox puede usar una extensión llamada FirePHP que permite el registro y descarga de información desde sus aplicaciones PHP a la consola. Este es un complemento de la extensión de desarrollo web impresionante Firebug .

Chrome

Sin embargo, si está utilizando Chrome, hay una herramienta de depuración de PHP llamada Chrome Registrador o webug (webug tiene problemas con el orden de los registros).

Más recientemente Clockwork está en desarrollo activo, lo que amplía las Herramientas de desarrollo al agregar un nuevo panel para proporcionar información útil de depuración y creación de perfiles. Proporciona soporte listo para usar para Laravel 4 y Slim 2 y se puede agregar soporte a través de su API extensible.

Usando Xdebug

Una mejor manera de depurar su PHP sería a través de Xdebug. La mayoría de los navegadores proporcionan extensiones de ayuda para ayudarlo a pasar la cadena de consulta/cookie requerida para inicializar el proceso de depuración.

 122
Author: Malachi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-14 18:21:09

O utiliza el truco de este sitio web Depurar PHP para consola

Primero necesitas una pequeña función auxiliar PHP

function debug_to_console( $data ) {
    $output = $data;
    if ( is_array( $output ) )
        $output = implode( ',', $output);

    echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}

Entonces puedes usarlo así

debug_to_console( "Test" );

Esto creará una salida como esta:

Debug Objects: Test
 281
Author: Senador,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-02 19:23:36

Si estás buscando un enfoque simple, echo como JSON:

<script>
    console.log(<?= json_encode($foo); ?>);
</script>
 54
Author: Travis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-01 00:23:51

De forma predeterminada, toda la salida va a stdout, que es la respuesta HTTP o la consola, dependiendo de si su script es ejecutado por Apache o manualmente en la línea de comandos. Pero puedes usar error_log para el registro y se pueden escribir varias corrientes de E/S con fwrite.

 32
Author: nikc.org,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-01 10:44:02

Prueba esto está funcionando:

echo("<script>console.log('PHP: ".$data."');</script>");
 26
Author: Mandy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-11 11:37:33

Algunas grandes respuestas que añaden más profundidad; pero necesitaba algo más simple y más como el comando JS console.log().

Uso PHP en muchas "recopilación de datos y convertir en xml" en la aplicación AJAX. el JS console.log no funciona en ese caso; rompe la salida xml. (Tal vez alguien tiene una solución para esto?)

Xdebug etc tenía problemas similares.

Mi solución en Windows:

  • Configurar un archivo .txt que es algo fácil de conseguir y escribible
  • Establecer el PHP error_log variable en el archivo .ini para escribir en ese archivo
  • Abra el archivo en el explorador de archivos de Windows y abra un panel de vista previa para él
  • Utilice el comando PHP error_log('myTest'); para enviar mensajes

Esta solución es simple, satisface mis necesidades la mayoría del tiempo, PHP estándar, y el panel de vista previa se actualiza automáticamente cada vez que PHP escribe en él.

 14
Author: Klompenrunner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-06 08:03:25

Como autor de la página web enlazada en la respuesta popular anterior, me gustaría agregar mi última versión de esta sencilla función auxiliar, mucho más sólida.

Utilizo json_encode() para hacer una comprobación para el tipo var no es necesario y añadir también un búfer para resolver problemas con frameworks, no tienen un retorno sólido o uso excesivo de header().

/**
 * Simple helper to debug to the console
 *
 * @param $data object, array, string $data
 * @param $context string  Optional a description.
 *
 * @return string
 */
function debug_to_console( $data, $context = 'Debug in Console' ) {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.
    ob_start();

    $output  = 'console.info( \'' . $context . ':\' );';
    $output .= 'console.log(' . json_encode( $data ) . ');';
    $output  = sprintf( '<script>%s</script>', $output );

    echo $output;
}

Uso

// $data is the example var, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console( $data );`

Captura de pantalla del resultado

También un ejemplo simple como imagen para entender mucho sencillo.

introduzca la descripción de la imagen aquí

 14
Author: bueltge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:32

Encuentro esto útil:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        if (is_array($data))
            $output = '<script>console.log("' . str_repeat(" ", $priority-1) . implode( ",", $data) . '");</script>';
        else
            $output = '<script>console.log("' . str_repeat(" ", $priority-1) . $data . '");</script>';

        echo $output;
    }
}

Y úsalo como:

<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important' ,1 , $debug);
console('Less Important' ,2 , $debug);
console('Even Less Important' ,5 , $debug);
console('Again Important' ,1 , $debug);
?>

Que sale en la consola:

Important
 Less Important
     Even Less Important
Again Important

Y puede desactivar los registros menos importantes limitándolos usando {debug value

 11
Author: zee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-15 11:34:05
    echo "<div display='none'><script type='text/javascript'>console.log('console log message')</script></div>";

Crea un

      <div>

Con el

    display="none"

De modo que el div no se muestra, pero el

    console.log()

La función se crea en javascript. Así que obtienes el mensaje en la consola.

 11
Author: Neo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-13 10:05:13
function phpconsole($label='var',$x){
 ?>
 <script type="text/javascript">
    console.log('<?php echo ($label)?>');
    console.log('<?php echo json_encode($x)?>');
    </script>
 <?php
}
 7
Author: ashraf mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-12 14:52:36

Corto y fácil, para arrays, cadenas o también objetos.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}
 7
Author: Carlos Lugo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 19:57:16

Creo que se puede usar {

function jsLogs($data) {
    $html = "";

    if (is_array($data) || is_object($data)) {
        $html = "<script>console.log('PHP: ".json_encode($data)."');</script>";
    } else {
        $html = "<script>console.log('PHP: ".$data."');</script>";
    }

    echo($html);
    # exit();
}

jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
jsLogs("testing string"); #PHP: testing string
 7
Author: Pankaj Bisht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-16 08:59:41

Si desea escribir en el archivo de registro PHP, y no en la consola JavaScript, puede usar esto:

error_log ( "This is logged only to the PHP log" )

Referencia: http://php.net/manual/en/function.error-log.php

 6
Author: Dan Green-Leipciger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 15:52:02

Para Chrome hay una extensión llamada Chrome Logger que permite registrar mensajes PHP.

Los DevTools de Firefox incluso tienen soporte integrado para el protocolo Chrome Logger.

Para habilitar el registro, solo tiene que guardar el 'ChromePhp.archivo php en su proyecto. Entonces se puede usar así:

include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');

Ejemplo tomado de la página de GitHub .

La salida puede verse como esto:

Registro del servidor dentro de Firefox DevTools

 5
Author: Sebastian Zartner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 10:05:29

También hay una gran extensión de Google Chrome PHP Console con php library que permite:

  • Consulte errores y excepciones en la consola de JavaScript de Chrome y en las ventanas emergentes de notificación.
  • Vuelca cualquier variable de tipo.
  • Ejecute código PHP de forma remota.
  • Proteger el acceso por contraseña.
  • Agrupa los registros de la consola a petición.
  • Saltar a archivo de error:línea en su editor de texto.
  • Copie los datos de error/depuración al portapapeles (para los probadores).
 4
Author: barbushin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-09 04:25:03

He abandonado todo lo anterior en favor de http://phptoolcase.com/guides/ptc-debug-guide.html no puedo alabar lo suficiente!

Simplemente haga clic en una de las pestañas en la parte superior derecha, o en el "clic aquí" para expandir/ocultar.

Observe las diferentes "categorías". Puede hacer clic en cualquier matriz a expandir/collpase ella.

Desde la página web

" Características principales:

Show globals vars ($GLOBALS, $_POST, $_GET, $_COOKIE ...)
Show php version and loaded extensions
Replace php built in error handler
Log sql queries
Monitor code and sql queries execution time
Inspect variables for changes
Function calls tracing
Code coverage analysis to check which lines of script where executed
Dump of all types of variable
File inspector with code highlighter to view source code
Send messages to js console(Chrome only), for ajax scripts

" introduzca la descripción de la imagen aquí

 3
Author: Mawg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-13 02:57:35

Gran post gracias, estaba buscando una manera de depurar el código en un plugin de Wordpress que estaba desarrollando y me encontré con este post.

Tomé los bits de código que son más aplicables a mí de las respuestas anteriores y los combiné en una función que puedo usar para depurar Wordpress. La función es:

function debug_log( $object=null, $label=null, $priority=1 ){
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('".str_repeat("-", $priority-1).$label."', ".$message.");</script>";
}

El uso es el siguiente:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log( $txt,'',7 );
debug_log( $sample_array );

Espero que alguien más encuentre útil esta función.

Si esta función se utiliza con el desarrollo de Wordpress, el la función debe colocarse en las funciones.php del tema hijo y luego puede ser llamado en cualquier parte del código.

 3
Author: Clinton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-05 08:59:51
$variable = "Variable";
echo "<script>console.log('$variable');</script>";

Interacción PHP y Javascript.

 3
Author: 0DAYanc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 23:42:36

A partir de 2017, firebug y, por lo tanto, firephp se han desactivado.

Escribí algunas pequeñas modificaciones a la herramienta chromephp para permitir la migración perfecta de firephp a firebug para depurar a través de la consola.

Este artículo explica en sencillos y claros pasos

Https://medium.com/@kudehinbuoluwaponle/migrate-from-firephp-to-chromephp-in-5-minutes-without-breaking-existing-code-e4afd1b28c5c

 2
Author: Kudehinbu Oluwaponle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-20 13:17:38

Para llamadas Ajax o respuestas xml / json, donde no desea interferir con el cuerpo, debe enviar registros a través de encabezados http y luego agregarlos a la consola con una extensión web. Así es como FirePHP y QuantumPHP (una bifurcación de ChromePHP) lo hacen en Firefox.

Si tiene paciencia, x-debug es una mejor opción: obtiene una visión más profunda de PHP, con la capacidad de pausar su script, ver lo que está sucediendo y luego reanudar el script.

 2
Author: Frank Forte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 05:01:36

Cualquiera de estos dos están funcionando:

<?php
    $five = 5;
    $six = 6;
?>
<script>
    console.log(<?php echo $five + $six ?>);
</script>


<?php
    $five = 5;
    $six = 6;
    echo("<script>console.log($five + $six);</script>");
?>
 1
Author: roybraym,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 06:08:52
function console_log( $data ) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if ( is_array( $data ) )
        error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . implode( ',', $data) );
    else
        error_log( end(split('/',$caller['file'])) . ':' . $caller['line'] . ' => ' . $data );

}
 0
Author: btm1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-11 05:44:57

Aquí hay una función útil. Es súper simple de usar, le permite pasar tantos argumentos como desee, de cualquier tipo, y mostrará el contenido del objeto en la ventana de la consola del navegador como si llamara a la consola.log desde JavaScript-pero desde PHP

Tenga en cuenta que también puede usar etiquetas pasando ' TAG-YourTag 'y se aplicará hasta que se lea otra etiqueta, por ejemplo,'TAG-YourNextTag'

/*
*   Brief:          Print to console.log() from PHP
*   Description:    Print as many strings,arrays, objects, and other data types to console.log from PHP.
*                   To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
*                   you can pass as many data as you want an this will still work.
*
*                   This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*                   
*                   A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
*                   detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
*                   be applied to all data after it.
*
*                   Example:
*                   consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3); 
*                   Result:
*                       FirstTag '...data...'
*                       FirstTag '...data2...'
*                       SecTag   '...data3...' 
*/
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){       
            if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
                $tag = substr($arg,4);
            }else{      
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('".$tag." ".$arg."');</script>";
            }       
        }
    }
}

NOTA: func_num_args() y func_num_args() son funciones de php para leer un número dinámico de args de entrada, y permitir que esta función tenga infinitamente muchos consola.registrar solicitudes de una llamada a función

 0
Author: Chris Sprague,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-26 12:45:31