Handle PHP errors, dump variables, execute PHP code remotely in Google Chrome

Overview

PHP Console server library

Author GitHub release Coverage Status Build Status Software License Packagist

PHP Console allows you to handle PHP errors & exceptions, dump variables, execute PHP code remotely and many other things using Google Chrome extension PHP Console and PhpConsole server library.

Overview

Requirements

For projects with PHP < 5.3 you can try to use old deprecated version of PHP Console. But mention that actual last version is much more functional.

Installation

Composer

{
	"require": {
		"php-console/php-console": "^3.1"
	}
}

Or

$ composer require php-console/php-console

Monolog handler

https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/PHPConsoleHandler.php

Symfony framework bundle

https://github.com/Vitre/php-console-bundle

Yii framework extension

http://www.yiiframework.com/extension/php-console

Slim framework

https://github.com/amenadiel/SlimPHPConsole (thanks to @amenadiel)

Silex framework service provider

https://github.com/barbushin/php-console-silex (thanks to @Chi-teck)

Laravel 4.* & 5.* framework service provider

https://github.com/barbushin/php-console-laravel

Drupal CMS module

https://drupal.org/project/pc (thanks to @Chi-teck)

WordPress plugin

https://github.com/unfulvio/wp-php-console (thanks to @nekojira)

Usage

You can try most of PHP Console features on live demo server.

Connector

There is a PhpConsole\Connector class that initializes connection between PHP server and Google Chrome extension. Connection is initialized when PhpConsole\Connector instance is initialized:

$connector = PhpConsole\Connector::getInstance();

Also it will be initialized when you call PhpConsole\Handler::getInstance() or PhpConsole\Helper::register().

Communication protocol

PHP Console uses headers to communicate with client, so PhpConsole\Connector::getInstance() or PhpConsole\Handler::getInstance() must be called before any output. If headers are sent before script shut down or PHP Console response package size is out of web-server headers size limit, then PHP Console will store response data in PhpConsole\Storage implementation and send it to client in STDOUT, in additional HTTP request. So there is no limit in PHP Console response package size.

Troubleshooting with $_SESSION handler overridden in some frameworks

By default PHP Console uses PhpConsole\Storage\Session for postponed responses, so all temporary data will be stored in $_SESSION. But there is some problem with frameworks like Symfony and Laravel that overrides PHP session handler. In this case you should use any other PhpConsole\Storage implementation like:

// Can be called only before PhpConsole\Connector::getInstance() and PhpConsole\Handler::getInstance()
PhpConsole\Connector::setPostponeStorage(new PhpConsole\Storage\File('/tmp/pc.data'));

See all available PhpConsole\Storage implementations in /src/PhpConsole/Storage.

Strip sources base path

If you want to see errors sources and traces paths more short, call:

$connector->setSourcesBasePath('/path/to/project');

So paths like /path/to/project/module/file.php will be displayed on client as /module/file.php.

Works with different server encodings

If your internal server encoding is not UTF-8, so you need to call:

$connector->setServerEncoding('CP1251');

Initialization performance

PhpConsole server library is optimized for lazy initialization only for clients that have Google Chrome extension PHP Console installed. There is example of correct initialization PhpConsole on your production server.

Protect connection

Protect by password

ScreenShot

$connector->setPassword('yohoho123', true);

Clients will need to enter a password to get access to PHP Console server data. All passwords are stored on client as SHA-256 hashes. Second argument says that the PHP Console authorization token will depend on the client IP.

SSL only connection mode

$connector->enableSslOnlyMode();

So all PHP Console clients will be automatically redirected to HTTPS.

Protect connection by list of allowed IP masks

$connector->setAllowedIpMasks(array('192.168.*.*', '2001:0:5ef5:79fb:*:*:*:*'));

Handle errors

ScreenShot

There is a PhpConsole\Handler class that initializes PHP errors & exceptions handlers and provides the next features:

  • Handle PHP errors (+fatal & memory limit errors) and exceptions.
  • Ignore repeated errors.
  • Call previously defined errors and exceptions handlers.
  • Handle caught exceptions using $handler->handleException($exception).
  • Debug vars using $handler->debug($var, 'some.tags').

Initialize PhpConsole\Handler in the top of your main project script:

$handler = PhpConsole\Handler::getInstance();
/* You can override default Handler behavior:
	$handler->setHandleErrors(false);  // disable errors handling
	$handler->setHandleExceptions(false); // disable exceptions handling
	$handler->setCallOldHandlers(false); // disable passing errors & exceptions to prviously defined handlers
*/
$handler->start(); // initialize handlers

Debug vars

ScreenShot

PHP Console has multifunctional and smart vars dumper that allows to

  • Dump any type variable.
  • Dump protected and private objects properties.
  • Limit dump by level, items count, item size and total size(see $connector->getDumper()).
  • Dump objects class name.
  • Smart dump of callbacks and Closure.
  • Detect dump call source & trace(call $connector->getDebugDispatcher()->detectTraceAndSource = true).

How to call

Longest native debug method call:

PhpConsole\Connector::getInstance()->getDebugDispatcher()->dispatchDebug($var, 'some.tags');

Shorter call debug from Handler:

PhpConsole\Handler::getInstance()->debug($var, 'some.tags');

Shortest call debug using global PC class

PhpConsole\Helper::register(); // it will register global PC class
// ...
PC::debug($var, 'tag');
PC::tag($var);

Custom call debug by user defined function

function d($var, $tags = null) {
	PhpConsole\Connector::getInstance()->getDebugDispatcher()->dispatchDebug($var, $tags, 1);
}
d($var, 'some.tags');

Tags

  • Debug tags argument is optional.
  • Tags is a string with tags separated by dot(e.g. "low.db").
  • Tags can be used to identify what exactly var was dumped.
  • You can configure client to ignore displaying some tags.

Remote PHP code execution

ScreenShot

PHP Console provide a way to execute PHP code on your server remotely, from Google Chrome extension terminal.

  • Remote PHP code execution allowed only in password protected mode
  • Every eval request is signed with unique SHA-256 token
  • Result contains: output, return and time data
  • Errors & exception occurred during PHP code execution will be handled

Configuration

$connector = PhpConsole\Connector::getInstance();
$connector->setPassword($password);

// Configure eval provider
$evalProvider = $connector->getEvalDispatcher()->getEvalProvider();
$evalProvider->addSharedVar('post', $_POST); // so "return $post" code will return $_POST
$evalProvider->setOpenBaseDirs(array(__DIR__)); // see http://php.net/open-basedir

$connector->startEvalRequestsListener(); // must be called in the end of all configurations

PSR-3 logger implementation

There is PHP Console implementation of PSR-3 interface. to integrate PHP Console with PSR-3 compitable loggers(e.g. Monolog). See PhpConsole\PsrLogger.

Jump to file

Read this article if you want to configure PHP Console extension to open errors/exceptions source file:line right in your IDE, just by click on the button in Notification popup.

Easy migrate from PhpConsole v1.x to v3.x

If you have used PhpConsole v1.x and want to migrate to v3.x without any code changes, so just use PhpConsole\OldVersionAdapter:

PhpConsole\OldVersionAdapter::register(); // register PhpConsole v1.x class emulator

// Call old PhpConsole v1 methods as is
PhpConsole::start(true, true, $_SERVER['DOCUMENT_ROOT']);
PhpConsole::debug('Debug using old method PhpConsole::debug()', 'some,tags');
debug('Debug using old function debug()', 'some,tags');
echo $undefinedVar;
PhpConsole::getInstance()->handleException(new Exception('test'));

// Call new PhpConsole methods, if you want :)
PhpConsole\Connector::getInstance()->setServerEncoding('cp1251');
PhpConsole\Helper::register();
PC::debug('Debug using new methods');

But, anyway, if you can't migrate to new version of PHP Console because of using PHP < 5.3 on your servers, then you can use old deprecated version of PHP Console.

Comments
  • Not Connecting from our server

    Not Connecting from our server

    We have php console installed via composer on a standalone domain on our server (no wordpress or similar application). Basically we have an app that is making calls to a php file, and in that php file we want to initialize the php console. However, we can't get it to send the request to authenticate and establish a connection. Right now we're testing our app in chrome from desktop (the app is currently web languages) Here's our initialization code.

    require DIR . '/vendor/autoload.php';
    $connector = PhpConsole\Connector::getInstance(); PhpConsole\Helper::register(); $connector->setPassword('123456', false); $connector->getDebugDispatcher()->dispatchDebug('ok'); PC::debug("our stuff");

    What are we doing wrong?

    opened by TheEmberLeader 20
  • undefined variable in background.js

    undefined variable in background.js

    Hey barbushin, I'm using your plugin in tandem with nekojira's wp one if that's important. When I reload a page on a develop site to get errors, I never see the password button to login, and I get an error when I inspect the extension in chrome. It says:

    extensions::uncaught_exception_handler:8 Error in response to tabs.get: TypeError: Cannot read property 'isSslOnlyMode' of undefined at D.a.q (chrome-extension://nfhmhhlpfleoednkpnnnkolmclajemef/background.js:25:173) at Object.callback (chrome-extension://nfhmhhlpfleoednkpnnnkolmclajemef/background.js:17:320) at x (chrome-extension://nfhmhhlpfleoednkpnnnkolmclajemef/background.js:17:232) at chrome-extension://nfhmhhlpfleoednkpnnnkolmclajemef/background.js:17:407 at XMLHttpRequest.l.onreadystatechange (chrome-extension://nfhmhhlpfleoednkpnnnkolmclajemef/background.js:19:105)

    Anyway, I'm not sure if this is related to nekojira or yourself. But any help would be appreciated.

    bug 
    opened by TheEmberLeader 19
  • PHPConsole stopped working / no icon

    PHPConsole stopped working / no icon

    PHPConsole was working for me fine for a long time but today the icon will not show and no debug logs are displaying in the console. This is effecting all developers on this product across multiple branches so while it is possible it is environmental it is not likely caused by a code change. I've tested personally on Windows 7 and Ubuntu 14.04.2 and others have reported on OSX as well.

    PHPConsole response headers look like this, but I'm not sure what successful ones are supposed to look like for comparison. PHP-Console:{"protocol":5,"auth":{"publicKey":"HEX STRING REMOVED","isSuccess":false},"docRoot":null,"sourcesBasePath":null,"getBackData":null,"isLocal":null,"isSslOnlyMode":false,"isEvalEnabled":null,"messages":[]} PHP-Console-Postpone:{"protocol":5,"isPostponed":true,"id":"169481652010446978121381394038"}

    opened by nhorvath 15
  • Apache24 + php7.0.3

    Apache24 + php7.0.3

    Hi there, got problem with remote code execution

    Server version: Apache/2.4.18 (FreeBSD) + PHP 7.0.3

    when i run

    return 2+2

    or other code that works up to php 5.6 for example: return ['SESSION' =>$_SESSION, 'GET'=>$_GET, 'POST' => $_POST, 'SERVER' => $_SERVER];

    and push ctrl+enter

    got error:

    E_WARNING Invalid argument supplied for foreach() - phar:///v/ftp/php70/lib/phpConsole.phar/EvalProvider.php:115

    when I run PC::debug directly form *.php file console works fine

    Second problem, when i do parse error now i have on console:

    E_ERROR  Uncaught TypeError: Argument 1 passed to PhpConsole\Handler::handleException() must be an instance of Exception, instance of ParseError given in phar:///v/ftp/php70/lib/phpConsole.phar/Handler.php:213
    Stack trace:
    #0 [internal function]: PhpConsole\Handler->handleException(Object(ParseError))
    #1 {main}
      thrown - phar:///v/ftp/php70/lib/phpConsole.phar/Handler.php:213
    

    my initialization for phpconsole looks like:

    require_once 'phar://' . __DIR__ . '/lib/phpConsole.phar';
    $connector = PhpConsole\Helper::register();
    if($connector->isActiveClient()) {
        $connector->setSourcesBasePath(__DIR__);
        $connector->setPassword('mysecret');
        $connector->getDebugDispatcher()->detectTraceAndSource = true;
        $evalProvider = $connector->getEvalDispatcher()->getEvalProvider();
        $evalProvider->disableFileAccessByOpenBaseDir();
        $evalProvider->addSharedVar('post', $_POST);
        $evalProvider->addSharedVar('get', $_GET);
        $evalProvider->addSharedVar('session', $_SESSION);
        $evalProvider->addSharedVar('server', $_SERVER);
        $connector->startEvalRequestsListener();
        $handler = PhpConsole\Handler::getInstance();
        $handler->setHandleErrors(true);
        $handler->setHandleExceptions(true);
        $handler->start();
    }
    
    opened by alfiqmiq 14
  • "Cannot send session cache limiter - headers already sent" when using PhpConsole in WordPress

    Hi Sergey,

    I had some people reporting an error with my WordPress implementation of PhpConsole I'm trying to solve: https://github.com/nekojira/wp-php-console/issues/11 Cannot send session cache limiter - headers already sent

    the error is triggered by PhpConsole/Storage/Session.php but it's related to a WordPress core file (https://github.com/nekojira/wp-php-console/issues/11#issuecomment-119005216)

    It's a bit difficult for me to replicate the error as it doesn't happen in every installation but only when some other plugins are installed, without a reference in the stack trace.

    Do you think there's something I can change in my PhpConsole implementation to avoid this kind of error?

    thank you!

    question 
    opened by unfulvio 14
  • Can't execute PHP code from Console:

    Can't execute PHP code from Console: "Wrong PHP Console eval request signature"

    I'm using the following instructions to connect the PHP Console client from Chrome to my PHP application.

        $handler = PhpConsole\Handler::getInstance();
        if ( PhpConsole\Handler::getInstance()->isStarted() != true )
            $handler->start();
    
        $connector = PhpConsole\Connector::getInstance();
        $connector->setAllowedIpMasks( array( '192.168.*.*' ) );
        $connector->setPassword( 'mypassword' );
        $connector->setSourcesBasePath( '/srv/www/my-path/' );
    
        $evalProvider = $connector->getEvalDispatcher()->getEvalProvider();
        $evalProvider->addSharedVarReference( 'post', $_POST );
    
        $connector->startEvalRequestsListener();
    

    However, when I try to execute anything from the PHP Console (e.g. $test = 'foo'; var_dump($test);), it will return an error from Chrome javascript console in dev tools:

        Wrong PHP Console eval request signature - '/my-path/php-console/php-console/src/PhpConsole/Connector.php:301'
    

    I checked the corresponding line, but couldn't figure out what I'm doing wrong. Does not seem a bug. I was unable to find the issue referenced elsewhere.

    opened by unfulvio 10
  • No extension icon in address bar & no data in console. OS X

    No extension icon in address bar & no data in console. OS X

    Testing on http://php-console.com/instance/examples/features/debug_vars.php Extension is installed and working (notification popups about are error are randomly popping out). Debug headers are visible in the browser. However, extension icon does not appear in the address bar and the output does not appear in the console. Looks like headers could not reach the extension.

    Tried on Chromium 33.0.1704.0 and Chrome 33.0.1750.117. Running on OS X 10.9.1. Any experimental flags should be set in about:flags?

    question client 
    opened by rainder 10
  • Problem with CodeIgniter redirect() method

    Problem with CodeIgniter redirect() method

    I am using with Codeigniter 3 (successfully used with CI before). No $_POST data is being processed, when I exclude the php-console files, it is working again, any tips?

    opened by wrabit 8
  • (feature request) Parse XMLHttpResponses?

    (feature request) Parse XMLHttpResponses?

    It would be awesome if php-console could recognize and parse XMLHttpResponses (similar to that of FirePHP).

    Or did I missing something, and it already does this?

    question client 
    opened by guice 7
  • PHP OOM errors when PHPConsole enabled

    PHP OOM errors when PHPConsole enabled

    This is kind of complicated to replicate, and I even took a while to nail down for sure that PHPConsole was causing it it but I will try to explain as best I can.

    Initially, PHPConsole will work fine, however after some use (maybe 30 mins of developing, so lots of page refreshes and page loads) the server will start returning 500 errors but most pages will actually load fine. The PHPConsole icon will disappear from the address bar. It must be that the errors occur during the flush handler for PHPConsole. PHP error log shows OOM errors but the strange thing is that the memory limit is set MUCH higher then the number in the error. Once the 500 errors start occurring they continue until cookies are cleared. Then they will go away for a similar period of time as the initial period and then reoccur.

    Disabling PHPConsole eliminates this issue.

    I've tried increasing the memory limit in php all the way up to absurd numbers but it doesn't help, the reported max in the OOM error message remains the same. PHP is reading the configs I set because ini_get('memory_limit') reflects the values I set it to.

    question server 
    opened by nhorvath 7
  • Illegal character encoding specified

    Illegal character encoding specified

    E_WARNING  mb_convert_encoding(): Illegal character encoding specified - /vendor/php-console/php-console/src/PhpConsole/Connector.php:362 
    

    My initialisation logic:

    if (PHP_CONSOLE) {
        $phpConsoleConnector = \PhpConsole\Connector::getInstance();
    
        if ($phpConsoleConnector->isActiveClient()) {
            $phpConsoleConnector->setSourcesBasePath(ROOT_PATH);
            $phpConsoleConnector->setPassword('password');
    
            \PhpConsole\Helper::register();
    
            $handler = PhpConsole\Handler::getInstance();
            $handler->start(); // initialize handlers
        }
    }
    
    bug server 
    opened by alexborisov 7
  • Error: Required parameter $args follows optional parameter $key

    Error: Required parameter $args follows optional parameter $key

    Required parameter $args follows optional parameter $key

    /home/runner/work/monolog-laminas-factory/monolog-laminas-factory/vendor/php-console/php-console/src/PhpConsole/Connector.php:377

    opened by mimmi20 0
  • Remove unncessary final, fixes PHP 8 compatibility

    Remove unncessary final, fixes PHP 8 compatibility

    Using this library on PHP 8 leads to this warning:

    PHP Warning: Private methods cannot be final as they are never overridden by other classes in vendor/php-console/php-console/src/PhpConsole/Connector.php on line 101

    This PR fixes that in a less intrusive way than #171

    closes #171

    opened by Seldaek 1
  • Warning: Private methods cannot be final as they are never overridden by other classes on php8-beta4

    Warning: Private methods cannot be final as they are never overridden by other classes on php8-beta4

    Warning: Private methods cannot be final as they are never overridden by other classes in /var/www/epmms/vendor/php-console/php-console/src/PhpConsole/Connector.php on line 101

    opened by haohetao 0
Releases(3.1.8)
The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function that you can use instead of var_dump().

VarDumper Component The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function t

Symfony 7.1k Jan 1, 2023
Laravel Dumper - Improve the default output of dump() and dd() in Laravel projects

Laravel Dumper Improve the default output of dump() and dd() in Laravel projects. Improves the default dump behavior for many core Laravel objects, in

Galahad 301 Dec 26, 2022
PHP errors for cool kids

whoops PHP errors for cool kids whoops is an error handler framework for PHP. Out-of-the-box, it provides a pretty error interface that helps you debu

Filipe Dobreira 12.9k Dec 24, 2022
😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.

Tracy - PHP debugger Introduction Tracy library is a useful helper for everyday PHP programmers. It helps you to: quickly detect and correct errors lo

Nette Foundation 1.6k Dec 23, 2022
Php Debugger to run in terminal to debug your code easily.

What is Dephpugger? Dephpugger (read depugger) is an open source lib to make a debug in php direct in terminal, without necessary configure an IDE. Th

Renato Cassino 190 Dec 3, 2022
Php Debugger to run in terminal to debug your code easily.

What is Dephpugger? Dephpugger (read depugger) is an open source library that allows a developer to debug in php direct in terminal, without necessary

Renato Cassino 190 Dec 3, 2022
PHP APM (Alternative PHP Monitor)

APM (Alternative PHP Monitor) APM (Alternative PHP Monitor) is a monitoring extension enabling native Application Performance Management (APM) for PHP

Patrick Allaert 310 Dec 4, 2022
Zipkin PHP is the official PHP Tracer implementation for Zipkin

Zipkin PHP is the official PHP Tracer implementation for Zipkin, supported by the OpenZipkin community. Installation composer require openz

Open Zipkin 250 Nov 12, 2022
Debug bar for PHP

PHP Debug Bar Displays a debug bar in the browser with information from php. No more var_dump() in your code! Features: Generic debug bar Easy to inte

Maxime Bouroumeau-Fuseau 4k Jan 8, 2023
Xdebug — Step Debugger and Debugging Aid for PHP

Xdebug Xdebug is a debugging tool for PHP. It provides step-debugging and a whole range of development aids, such as stack traces, a code profiler, fe

Xdebug 2.8k Jan 3, 2023
Kint - a powerful and modern PHP debugging tool.

Kint - debugging helper for PHP developers What am I looking at? At first glance Kint is just a pretty replacement for var_dump(), print_r() and debug

null 2.7k Dec 25, 2022
PHP Benchmarking framework

PHPBench is a benchmark runner for PHP analogous to PHPUnit but for performance rather than correctness. Features include: Revolutions: Repeat your co

PHPBench 1.7k Jan 2, 2023
The Interactive PHP Debugger

The interactive PHP debugger Implemented as a SAPI module, phpdbg can exert complete control over the environment without impacting the functionality

Joe Watkins 841 Oct 9, 2022
Dontbug is a reverse debugger for PHP

Dontbug Debugger Dontbug is a reverse debugger (aka time travel debugger) for PHP. It allows you to record the execution of PHP scripts (in command li

Sidharth Kshatriya 709 Dec 30, 2022
PHP Debug Console

PHP Console A web console to try your PHP code into Creating a test file or using php's interactive mode can be a bit cumbersome to try random php sni

Jordi Boggiano 523 Nov 7, 2022
PCOV - CodeCoverage compatible driver for PHP

PCOV A self contained CodeCoverage compatible driver for PHP Requirements and Installation See INSTALL.md API /** * Shall start recording coverage in

Joe Watkins 613 Dec 21, 2022
Low-overhead sampling profiler for PHP 7+

phpspy phpspy is a low-overhead sampling profiler for PHP. For now, it works with Linux 3.2+ x86_64 non-ZTS PHP 7.0+ with CLI, Apache, and FPM SAPIs.

Adam 1.3k Dec 24, 2022
Clockwork - php dev tools in your browser - server-side component

Clockwork is a development tool for PHP available right in your browser. Clockwork gives you an insight into your application runtime - including requ

its 4.8k Dec 29, 2022
Laravel Debugbar (Integrates PHP Debug Bar)

Laravel Debugbar This is a package to integrate PHP Debug Bar with Laravel. It includes a ServiceProvider to register the debugbar and attach it to th

Barry vd. Heuvel 14.8k Jan 9, 2023