15

I have a php file which is part of a wordpress plugin. I need to debug an issue we are having. I want to find out what a variable's value is. How can I print the variable's value to console? echo or chrome or firefox extensions have been suggested. I couldn't get echo to output to console (echo “$variablename";) and neither using the firephp extension for firefox.

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
grabury
  • 4,797
  • 14
  • 67
  • 125
  • Assuming you don't want to just dump the value right on the page with `var_dump()`, why not output the value to a temporary log file using `file_put_contents()`? – Ian Drake Oct 21 '15 at 17:59

4 Answers4

22

To answer your question, you can do this:

echo '<script>console.log("PHP error: ' . $error . '")</script>';

but I would recommend doing one of the things @Ishas suggested instead. Make sure $error doesn't contain anything that can mess up your script.

Josef Engelfrost
  • 2,955
  • 1
  • 29
  • 38
10

If you are thinking about the javascript console, you can not do this from PHP.

You have a few options you could choose from:

For a quick check for a variables value I would use var_dump, it will also show you the data type of the variable. This will be output to the browser when you request the page.

lshas
  • 1,691
  • 1
  • 19
  • 39
6

Logging to the DevTools console from PHP in WordPress

Debugging WooCommerce in WordPress with console_log in the Firefox DevTools

Here you can see my solution for the problem in action while debugging coupon logic in WooCommerce. This solution is meant for debug purposes, only. (Note: Screenshot not up to date, it will also expose private members.)

Features

  • Allow printing before and after rendering has started
  • Works in front-end and back-end
  • Print any amount of variables
  • Encode arrays and objects
  • Expose private and protected members of objects
  • Also log to the log file
  • Safely and easily opt-out in the production environment (in case you keep the calls)
  • Print the caller class, function and hook (quality of life improvement)

Solution

wp-debug.php

function console_log(): string {
    list( , $caller ) = debug_backtrace( false );
    $action = current_action();
    $encoded_args = [];
    foreach ( func_get_args() as $arg ) try {
        if ( is_object( $arg ) ) {
            $extract_props = function( $obj ) use ( &$extract_props ): array {
                $members = [];
                $class = get_class( $obj );
                foreach ( ( new ReflectionClass( $class ) )->getProperties() as $prop ) {
                    $prop->setAccessible( true );
                    $name = $prop->getName();
                    if ( isset( $obj->{$name} ) ) {
                        $value = $prop->getValue( $obj );
                        if ( is_array( $value ) ) {
                            $members[$name] = [];
                            foreach ( $value as $item ) {
                                if ( is_object( $item ) ) {
                                    $itemArray = $extract_props( $item );
                                    $members[$name][] = $itemArray;
                                } else {
                                    $members[$name][] = $item;
                                }
                            }
                        } else if ( is_object( $value ) ) {
                            $members[$name] = $extract_props( $value );
                        } else $members[$name] = $value;
                    }
                }
                return $members;
            };

            $encoded_args[] = json_encode( $extract_props( $arg ) );
        } else {
            $encoded_args[] = json_encode( $arg );
        }
    } catch ( Exception $ex ) {
        $encoded_args[] = '`' . print_r( $arg, true ) . '`';
    }
    $msg = '``, `'
        . ( array_key_exists( 'class', $caller ) ? $caller['class'] : "\x3croot\x3e" )
        . '\\\\'
        . $caller['function'] . '()`, '
        . ( strlen( $action ) > 0 ? '``, `' . $action . '`, ' : '' )
        . '` ➡️ `, ' . implode( ', ', $encoded_args );
    $html = '<script type="text/javascript">console.log(' . $msg . ')</script>';
    add_action( 'wp_enqueue_scripts', function() use ( $html ) {
        echo $html;
    } );
    add_action( 'admin_enqueue_scripts', function() use ( $html ) {
        echo $html;
    } );
    error_log( $msg );
    return $html;
}

wp-config.php (partially)

// ...

define( 'WP_DEBUG', true );

// ...

/** Include WP debug helper */
if ( defined( 'WP_DEBUG' ) && WP_DEBUG && file_exists( ABSPATH . 'wp-debug.php' ) ) {
    include_once ABSPATH . 'wp-debug.php';
}
if ( ! function_exists( 'console_log' ) ) {
    function console_log() {
    }
}

/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );

Usage

  • Before the HTML <head> is rendered:
console_log( $myObj, $myArray, 123, "test" );
  • After the HTML <head> is rendered (in templates, etc. / use when the above does not work):
echo console_log( $myObj, $myArray, 123, "test" );

Output format

 <caller class>\<caller function>()  <caller action/hook>  ➡️  <variables ...>

Special thanks to

Martin Braun
  • 10,906
  • 9
  • 64
  • 105
  • Hi, in my WP installation folder I created file "wp-debug.php" (same folder as "wp-config.php"): Then I editted my "wp-config.php" - set WP_DEBUG to true and after that I added your code (/** Include WP debug helper */ with 2 IFs). Whats the next step to print some data to console? Should I add "echo console_log( $myObj, $myArray, 123, "test" );" to my WP plugin code? Or should I write it to browser console? – Shortik Aug 03 '22 at 14:52
  • @Shortik Hey, sorry for the late reply. `echo console_log( $myObj, $myArray, 123, "test" );` is an example how to use the code and you would use it in any PHP code that will be executed on page load. The purpose is to get your PHP variables content into the JavaScript devtools console in your browser, so you put the code in the PHP code where you need to debug your PHP. It's not magic that will expose the full PHP environment to your console, instead it's more of a bridge that will allow you to print your PHP objects in the console in JSON format to inspect freely. Hope that helps. – Martin Braun Aug 10 '22 at 19:56
1

You can write a utility function like this:

function prefix_console_log_message( $message ) {

    $message = htmlspecialchars( stripslashes( $message ) );
    //Replacing Quotes, so that it does not mess up the script
    $message = str_replace( '"', "-", $message );
    $message = str_replace( "'", "-", $message );

    return "<script>console.log('{$message}')</script>";
}

The you may call the function like this:

echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" );

and this will output to console like this:

Error Message: This is really a -unique- problem!

Notice the quotes replaced with "-". It is done so that message does not mess up your script as pointed by @Josef-Engelfrost

You may also go one step further and do something like this:

function prefix_console_log_message( $message, $type = "log" ) {

    $message_types = array( 'log', 'error', 'warn', 'info' );
    $type          = ( in_array( strtolower( $type ), $message_types ) ) ? strtolower( $type ) : $message_types[0];
    $message       = htmlspecialchars( stripslashes( $message ) );
    //Replacing Quotes, so that it does not mess up the script
    $message = str_replace( '"', "-", $message );
    $message = str_replace( "'", "-", $message );

    return "<script>console.{$type}('{$message}')</script>";
}

and call the function like this:

echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" , 'error');

It will output error in console.

Rao Abid
  • 510
  • 4
  • 6