- Отладка PHP кода с помощью консоли JavaScript браузера
- 5 последних уроков рубрики «PHP»
- Фильтрация данных с помощью zend-filter
- Контекстное экранирование с помощью zend-escaper
- Подключение Zend модулей к Expressive
- Совет: отправка информации в Google Analytics через API
- Подборка PHP песочниц
- Browser debugging extensions
- Install the PHP plugin
- Configure Xdebug Helper for Chrome
- Configure Zend Debugger Toolbar for Firefox
- Browser debugging extensions
- Configure Xdebug Helper for Chrome
- Configure Zend Debugger Toolbar for Firefox
- Mastering PHP Console Logging: Tips and Best Practices for Debugging
- Using json_encode function to log PHP output to the console
- Using PHPDebugConsole to display log information
- PHP Echo & Print Statements — How to Output to the Browser
Отладка 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
Просмотров: 51553
Правила перепечатки
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 сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
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.
Install the PHP plugin
This functionality relies on the PHP plugin, which you need to install and enable.
The PHP plugin is available only in IntelliJ IDEA Ultimate.
- Press Control+Alt+S to open the IDE settings and then select Plugins .
- Open the Marketplace tab, find the PHP plugin, and click Install (restart the IDE if prompted).
Configure Xdebug Helper for Chrome
- Install the Xdebug helper extension for Chrome from the Chrome Web Store.
- In IntelliJ IDEA, 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 IntelliJ IDEA, 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 Languages & Frameworks | PHP | Debug page of the IDE settings Control+Alt+S .
- Initiate connection from the browser side. Click the Zend Debugger icon on the browser toolbar to initiate a debugging or profiling session:
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:
Mastering PHP Console Logging: Tips and Best Practices for Debugging
Learn how to log PHP data to the browser console using json_encode, PHPDebugConsole, and the echo command. Get helpful tips and best practices for debugging web applications.
PHP is an extensively used programming language for web development. Developers often need to debug their code to ensure it runs efficiently and as intended. One way to debug code is to output PHP data to the browser console. This technique helps developers to view debug information in real-time, which helps in identifying and fixing errors quickly. In this article, we’ll explore some of the most commonly used methods for logging PHP data to the browser console and discuss the best practices and tips for debugging.
Using json_encode function to log PHP output to the console
The json_encode function is a simple way to convert PHP data to JSON format, which can then be output to the console using console.log() in JavaScript. Here’s an example code:
$data = array('name' => 'John', 'age' => 30); echo '';
Using the json_encode function is useful when dealing with simple data types. However, it may not preserve complex data structures.
Using PHPDebugConsole to display log information
PHPDebugConsole is a logger/console class for PHP that provides multiple simultaneous output options, including the browser console. It is a powerful tool that offers customizable output formatting and filtering. Here’s an example code:
use PhpDebugConsole\Debug as debug; debug::console('Hello World!');
PHPDebugConsole also provides the ability to log complex data structures. However, it requires additional setup and configuration compared to other methods.
PHP Echo & Print Statements — How to Output to the Browser
PHP #aBaBaCaDaFEcho & PrintzXzXmPeRwV# Statements — How to Output to the Browser & Terminal. Duration: 8:15