- Browser debugging extensions
- Configure Xdebug Helper for Chrome
- Configure Zend Debugger Toolbar for Firefox
- Отладка PHP кода с помощью консоли JavaScript браузера
- 5 последних уроков рубрики «PHP»
- Фильтрация данных с помощью zend-filter
- Контекстное экранирование с помощью zend-escaper
- Подключение Zend модулей к Expressive
- Совет: отправка информации в Google Analytics через API
- Подборка PHP песочниц
- Tournas Dimitrios
- How to Debug PHP Code with Your Browser’s Console Tab September 7, 2012
Browser debugging extensions
In order to start debugging, you first need to activate the debugger engine on the server. To do this, you need to set a special GET/POST or COOKIE parameter (see the Xdebug and Zend Debugger official documentation for details). While you can do it manually, it is more convenient to use a browser extension, which lets you enable the debugger with a single click.
The following table lists the available debugging extensions.
Z-Ray for Zend Server version 7 or later. PhpStorm bookmarklets generator otherwise.
Configure Xdebug Helper for Chrome
- Install the Xdebug helper extension for Chrome from the Chrome Web Store.
- In PhpStorm, enable listening to incoming debug connections by either clicking on the toolbar or selecting Run | Start Listening for PHP Debug Connections
- Initiate connection from the browser side. Click the Xdebug Helper icon on the browser toolbar to initiate a debugging, profiling or tracing session:
- As a rule, no further configuration is required. If necessary, you can explore additional settings by right-clicking the Xdebug Helper icon and choosing Options from the context menu.
Configure Zend Debugger Toolbar for Firefox
- Install Zend Debugger Toolbar.
- In PhpStorm, enable listening to incoming debug connections by either clicking on the toolbar or selecting Run | Start Listening for PHP Debug Connections
- In the browser, click the Zend Debugger icon on the toolbar and select Settings . Make sure that Autodetect is selected, and the Broadcasting port value matches the value set for Settings broadcasting port on the PHP | Debug page of the IDE settings Ctrl+Alt+S .
- Initiate connection from the browser side. Click the Zend Debugger icon on the browser toolbar to initiate a debugging or profiling session:
Отладка PHP кода с помощью консоли JavaScript браузера
Отладка PHP кода выполняется самыми разными способами. Можно выводить информацию на экран, с помощью die или var_dump, с помощью файлов журнала, в которые пишутся сообщения об ошибках и предупреждения. Плохо то, что почти все перечисленные методы вносят нарушения в шаблон страниц и сообщения достаточно трудно вычленять в потоке другой информации.
Почему бы не использовать один инструмент для всех скриптов (и PHP и Javascript)? Таким инструментом может стать консоль JavaScript, которую можно использовать и для отладки PHP кода. Консоль входит в набор разработчика, который присутствует практически во всех современных браузерах по умолчанию или доступен в виде удобного дополнения. Она предоставляет собой отличный инструмент для цветного вывода с номером строки и всем, что нужно. А кроме того, можно выводить значения массивов и целых объектов в консоль.
Конечно, есть браузеры, в которых консоль отсутствует (например, IE) и инструмент отладки может нарушить процесс выполнения приложения. Но мы позаботимся, чтобы все проходило отлично.
Вот класс, который выполняет всю работу:
class PHPDebug < function __construct() < if (!defined("LOG")) define("LOG",1); if (!defined("INFO")) define("INFO",2); if (!defined("WARN")) define("WARN",3); if (!defined("ERROR")) define("ERROR",4); define("NL","\r\n"); echo ''; /// Конец секции для браузеров без консоли > function debug($name, $var = null, $type = LOG) < echo ''.NL; > >
Код достаточно простой и понятный. Основная идея заключается в генерировании JavaScript кода, который выводит значения переменных и сообщения в консоль. Очень просто и эффективно.
Код, который содержится в секции для браузеров без консоли, создает пустые функции-заглушки и браузер будет выполнять скрипт, несмотря на присутствующие вызовы записи сообщений в консоль.
Теперь посмотрим на пример использования. Ниже приведенный код используется в демонстрационной странице:
// Включаем код для отладки и определяем объект require_once("PHPDebug.php"); $debug = new PHPDebug(); // Простое сообщение на консоль $debug->debug("Очень простое сообщение на консоль"); // Вывод переменной на консоль $x = 3; $y = 5; $z = $x/$y; $debug->debug("Переменная Z: ", $z); // Предупреждение $debug->debug("Простое предупреждение", null, WARN); // Информация $debug->debug("Простое информационное сообщение", null, INFO); // Ошибка $debug->debug("Простое сообщение об ошибке", null, ERROR); // Выводим массив в консоль $fruits = array("банан", "яблоко", "клубника", "ананас"); $fruits = array_reverse($fruits); $debug->debug("Массив фруктов:", $fruits); // Выводим объект на консоль $book = new stdClass; $book->title = "Гарри Потный и кто-то из Ашхабада"; $book->author = "Д. K. Роулинг"; $book->publisher = "Arthur A. Levine Books"; $book->amazon_link = "http://www.amazon.com/dp/0439136369/"; $debug->debug("Объект: ", $book);
Чтобы увидеть действие кода, надо открыть консоль JavaScript в браузере и открыть/перегрузить демонстрационную страницу.
В браузерах без консоли в коде появятся элементы div с сообщениями, а код выполнится до конца без перерывов.
Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: www.codeforest.net/debugging-php-in-browsers-javascript-console
Перевел: Сергей Фастунов
Урок создан: 28 Марта 2011
Просмотров: 51537
Правила перепечатки
5 последних уроков рубрики «PHP»
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
Tournas Dimitrios
How to Debug PHP Code with Your Browser’s Console Tab September 7, 2012
Debugging PHP applications has always been a common activity , as no matter the experience of the developer , there is almost always a bit of syntax error (at least , it happens to me often) . For a quick and simple debugging process , the “echo” statement is probably the most used tool (combined with one of these three variables : var_dump , print_r , var_export() ) . While there are tools that reveal more details during debugging (such as XDebug) , you don’t always have access to install them on the server you’re working with . Fortunately, you can also gain some reasonable PHP-debugging capabilities through your browser’s web-development tool . Today’s article will present a way to extend the functionality of two open-source browsers (Firefox and Chrome) by installing plugins . The PHP-script will dump errors , traces or objects’s data into the browser’s enabled PHP-console .
Extending Chrome :
- Install the extension (ChromePHP) from the Google Chrome Extension Gallery into Chrome . A successful installation is notified by an icon on Chrome’s toolbar .
- Download from GitHub the ChromePhp class for logging and put it somewhere in your include path .This class allows you to log variables to the Chrome console .
- Write code into your PHP-script
include ‘ChromePhp.php’; ChromePhp::log(‘This is just a log message’); ChromePhp::warn(«This is a warning message » ) ; ChromePhp::error(«This is an error message» ) ; ChromePhp::log($_SERVER); // using labels foreach ($_SERVER as $key => $value)
Open Chrome and Click the extension icon to enable logging (the icon becomes light-blue) . If all is working correctly then your output will look something like this
Make sure you only include this in a development environment. You don’t want users seeing your debug statements on production.
Extending Mozilla FireFox :
While previous method is simple to implement on a hosting environment , this example is tedious if you are not comfortable with installing PEAR-packages . For starters , my previous article explains how to install PEAR-packages on WAMP in ten steps .
- Install into FF the following two extensions , Firebug and FirePHP .
- install PEAR’s “Log package ( pear install Log-1.12.7 ) . Notice the version .
- First set an extra repository in the list and install FirePHP Core Library from PEAR channel
pear channel-discover pear.firephp.org
pear install firephp/FirePHPCore - Write a simple Log-message
10, 'j'=>20 , 'd'=>'John Doe' , 'e'=>'Peter Armstrong'); $firephp->log($var, 'Iterators'); $firephp->log('Hello , this is a message from FirePHP'); ?>
This demonstration is just a limited subset of the functionality available through FirePHP . For more information visit FirePHP’s user-documentation at this link . . This reference has everything needed for using FirePHP to its greatest debugging capabilities .
Keep smiling and ….. Happy debugging 🙂 .