Как в php вывести в консоль браузера
Используя интерактивную консоль, можно ввести и выполнить непосредственно PHP-код.
Интерактивная консоль также автодополняет (с помощью клавиши Tab) имена функций, констант, классов, переменных, вызовы статических методов и константы классов.
Двойное нажатие клавиши Tab при наличии нескольких вариантов дополнения покажет список этих вариантов:
Когда есть только одно дополнение, одиночное нажатие Tab дополнит оставшийся текст на той же самой строке:
Дополнение также работает для имён, которые были объявлены в течение данной интерактивной сессии:
Интерактивная консоль хранит историю команд, для доступа к которой можно использовать стрелки вверх и вниз. История хранится в файле
Также можно устанавливать настройки php.ini в интерактивной консоли, используя специальное сокращение.
Используя обратные апострофы можно задать PHP-код, который выполнится в приглашении на ввод команды:
Установка less для постраничного вывода данных:
Замечание:
Файлы, подключённые с помощью опций auto_prepend_file и auto_append_file обрабатываются в этом режиме с некоторыми ограничениями, например, функции должны быть объявлены до их использования.
Интерактивный режим
User Contributed Notes 6 notes
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.
If you type 'php -a' and get a response of 'Interactive Shell' followed by a 'php>' prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.
You can also check 'php -m' and see if readline is listed in the output - if not, you don't have interactive shell.
Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you're done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file - hence you start in interactive mode with '<?php' in order to execute code.
Interactive shell evaluates every expression as you complete it (with ; or >), reports errors without terminating execution, and supports standard shell functionality via readline (history, tab completion, etc). It's an enhanced version of interactive mode that is ONLY available if you have the required libraries, and is an actual PHP shell that interprets everything you type as PHP code - using '<?php' will cause a parse error.
Finally, if you're running on Windows, you're probably screwed. From what I'm seeing in other comments here, you don't have readline, and without readline there is no interactive shell.
Почему бы не использовать один инструмент для всех скриптов (и PHP и Javascript)? Таким инструментом может стать консоль JavaScript, которую можно использовать и для отладки PHP кода. Консоль входит в набор разработчика, который присутствует практически во всех современных браузерах по умолчанию или доступен в виде удобного дополнения. Она предоставляет собой отличный инструмент для цветного вывода с номером строки и всем, что нужно. А кроме того, можно выводить значения массивов и целых объектов в консоль.
Конечно, есть браузеры, в которых консоль отсутствует (например, IE) и инструмент отладки может нарушить процесс выполнения приложения. Но мы позаботимся, чтобы все проходило отлично.
Вот класс, который выполняет всю работу:
Теперь посмотрим на пример использования. Ниже приведенный код используется в демонстрационной странице:
Чтобы увидеть действие кода, надо открыть консоль JavaScript в браузере и открыть/перегрузить демонстрационную страницу.
5 последних уроков рубрики "PHP"
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза "фильтруйте всё, экранируйте всё" всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
I find it very useful to print out to the browsers console instead of just var_dumping:
function console_log( $data ) echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
>
Usage:
$myvar = array(1,2,3);
console_log( $myvar ); // [1,2,3]
A good example of data output to the console via <script> tags, I myself used this first, but he broke the captcha job, because <script> tags were inserted into the base64 code of the captcha picture. Then I began to display logs in the headers with such a function (it may help someone else, in a similar situation):
function header_log ( $data ) $bt = debug_backtrace ();
$caller = array_shift ( $bt );
$line = $caller [ 'line' ];
$file = array_pop ( explode ( '/' , $caller [ 'file' ]));
header ( 'log_' . $file . '_' . $caller [ 'line' ]. ': ' . json_encode ( $data ));
>
?>
Usage:
$myvar = array(1,2,3);
header_log( $myvar ); // in headers we see: log_filename_rownumber: [1,2,3]
For me, just outputting variables only works when I know a method should be broken.
I use Xdebug in PHP Storm (available on other IDE's and editors as well)
It allows me to use line breaks and fully inspect anything that's set and how their values are changed and allows me to call single method even at (paused) runtime to see what behaviour the method really gives at any given point, which gives me a much better insight on how my code works and how to get it to work like it should.
I wholeheartedly recomend anyone to try a fuller-fledged debugger like that!
I am using two ways to debug code
one is print the data and die the function in specific point.
second one is writing log file in specific point in code.
function write_log($log_msg)
$log_filename = "logs";
if (!file_exists($log_filename))
mkdir($log_filename, 0777, true);
>
$log_file_data = $log_filename.'/debug.log';
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
write_log("Writing Log");
$a = array(
array('id' => '1','date' => '09-04-2018','length' => '10'),
array('id' => '2','date' => '09-04-2018','length' => '20'),
array('id' => '1','date' => '10-04-2018','length' => '11')
);
write_log(print_r($a,1));
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug. If you're interested in knowing the full contents of an object/array/scalar, then use
None of the given examples here do fit my needs.
When I debug, I want to see clearly what's going on and where is the debug data. Also it has to accommodate with the current styles and not fall behind or get mixed with other text etc.
This snippet will give you real debug notices in a flashy table:
- complete backtrace of calls on the left with line numbers
- arguments content on the right, with the variable name and coloring per variable type
well this is also very beneficial
I often rely on a Slack channel open that is solely dedicated to debug output in whatever project I'm working on. Then I use a PHP function called debug($obj) that takes $obj and uses the Slack API to post a message with that value to that channel. It's helped me immensely and hopefully it would help others too.p_r() is a function for logging variable values.
In this example the function p_r() does only log when the URL parameter d=<nonzero> is set. Reset it by d=0.
When the parameter is a valid filename (relative to the script's path) it will be logged to that file rather than to the browser.
function p_r($exp)
$res = "";
$trace = debug_backtrace();
$level = 0;
$e = error_reporting(E_ALL&
E_NOTICE);
$file = strrpos($trace[$level]['file'], "/");
$file = substr($trace[$level]['file'],$file+1);
$line = date("H:i:s"). " " . $file . ' ' . $trace[$level]['line'] . ' ' . $trace[$level+1]['function'] . "()";
$e = error_reporting($e);
if (!is_string($exp)) $exp = var_export($exp,1);
if (substr($_SESSION["d"],-4)==".log") file_put_contents ($_SESSION["d"],$line . ": ". $exp . "\n", FILE_APPEND);
> else $res = $line . "\n<pre>".htmlentities($exp). "</pre>\n";
echo $res;
>
return $res;
>
// refresh to prevent timeout
$a = $_SESSION['d'];
$_SESSION['d'] = $a;
error_reporting (E_ALL);
> else function p_r() <>
> // end if debug
if (! function_exists ( 'dd' )) /**
* 测试打印函数
* @param [type] $arr [description]
* @return [type] [description]
*/
function dd ( $arr ) if ( is_array ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
> else if ( is_object ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
if (! function_exists ( 'pp' )) /**
* 格式化输出
* @param [type] $arr [description]
* @return [type] [description]
*/
function pp ( $arr ) if ( is_array ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
> else if ( is_object ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
if (! function_exists ( 'pr' )) /**
* 打印不中断
*/
function pr ( $arr ) if ( is_array ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
> else if ( is_object ( $arr )) echo "<pre>" ;
print_r ( $arr );
echo "</pre>" ;
if (! function_exists ( 'vd' )) /**
* 测试打印函数
* @param [type] $arr [description]
* @return [type] [description]
*/
function vd ( $arr ) echo "<pre>" ;
var_dump ( $arr );
echo "</pre>" ;
die;
>
>
if (! function_exists ( 'vv' )) function vv ( $arr ) echo "<pre>" ;
var_dump ( $arr );
echo "</pre>" ;
>
>
if (! function_exists ( 'console_log' )) /**
* console.log控制台调试函数
* @param [type] $data [要在控制台输出的数据 支持数组、对象和字符串]
* @return [type] [description]
*/
function console_log ( $data ) if ( is_array ( $data ) || is_object ( $data )) echo ( "<script>console.log('" . json_encode ( $data ) . "');</script>" );
> else echo ( "<script>console.log('" . $data . "');</script>" );
>
>
>
/**
* 浏览器友好的变量输出,便于调试时候使用
*
* @param mixed $var 要输出查看的内容
* @param bool $echo 是否直接输出
* @param string $label 加上说明标签,如果有,这显示"标签名:"这种形式
* @param bool $strict 是否严格过滤
* @return string
*/
if (! function_exists ( 'dump' )) function dump ( $var , $echo = true , $label = null , $strict = true ) $label = ( $label === null ) ? '' : rtrim ( $label ) . ' ' ;
if (! $strict ) if ( ini_get ( 'html_errors' )) $output = print_r ( $var , true );
$output = "<pre>" . $label . htmlspecialchars ( $output , ENT_QUOTES ) . "</pre>" ;
> else $output = $label . " : " . print_r ( $var , true );
>
> else ob_start ();
var_dump ( $var );
$output = ob_get_clean ();
if (! extension_loaded ( 'xdebug' )) $output = preg_replace ( "/\]\=\>\n(\s+)/m" , "] => " , $output );
$output = '<pre>' . $label . htmlspecialchars ( $output , ENT_QUOTES ) . '</pre>' ;
>
>
if ( $echo ) echo ( $output );
return null ;
> else return $output ;
>
Is it possible write a string or log into the console?
What I mean
Just like in JSP, if we print something like system.out.println("some") , it will be there at the console, not at a page.
30 Answers 30
Or you use the trick from PHP Debug to console.
First you need a little PHP helper function
Then you can use it like this:
This will create an output like this:
1,994 1 1 gold badge 26 26 silver badges 35 35 bronze badges 5,010 2 2 gold badges 14 14 silver badges 12 12 bronze badges Thanks for the hint to my post. But the time and the knowledge has changed, the function also ;) I have it update now. OP states he wanted to print to standard output, not to html/js console.Firefox
On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.
Chrome
However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).
More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.
Using Xdebug
A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.
- Chrome - Xdebug Helper
- Firefox - The easiest Xdebug
- Opera - Xdebug
- Safari - Xdebug Toggler
If you're looking for a simple approach, echo as JSON:
29.2k 7 7 gold badges 114 114 silver badges 122 122 bronze badges OP states he wanted to print to standard output, not to html/js console. @beppe9000 That is incorrect. The OP asks if he can write from PHP to the console. Quote: "Is it possible write string or log into the console?" with this you can avoid var_dumps and similar. Works great and the console lets you toggle the json in a nice way. 15.3k 6 6 gold badges 45 45 silver badges 81 81 bronze badges Thanks, error_log is what I needed to output to the terminal from the PHP built-in web serverTry the following. It is working:
As the author of the linked webpage in the popular answer, I would like to add my last version of this simple helper function. It is much more solid.
I use json_encode() to check if the variable type is unnecessary and add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of header() .
Also, a simple example as an image to understand it much easier:
so that the div is not displayed, but the
function is created in javascript. So you get the message in the console.
PHP and JavaScript interaction.
I think it can be used --
Some great answers that add more depth; but I needed something simpler and more like the JavaScript console.log() command.
I use PHP in a lot of "gathering data and turn into XML" in Ajax applications. The JavaScript console.log doesn't work in that case; it breaks the XML output.
Xdebug, etc. had similar issues.
My solution in Windows:
- Setup a .txt file that is somewhat easily to get to and writable
- Set the PHP error_log variable in the .ini file to write to that file
- Open the file in Windows File Explorer and open a preview pane for it
- Use the error_log('myTest'); PHP command to send messages
This solution is simple and meets my needs most of the time. Standard PHP, and the preview pane automatically updates every time PHP writes to it.
I find this helpful:
And use it like:
Which outputs in console:
And you can switch off less important logs by limiting them using the $debug value.
@HattrickNZ This is to allow you to have different levels of log messages. If you are debugging you might want to show a very chatty stream of message with lots of info, however during normal operations you might set debug to 1 so you only get the most important errors/log items displayed. Its up to you to decide what items are important when writing the code. OP states he wanted to print to standard output, not to html/js console. @Peter Mortensen - true story! Edited this over 4yo post! :)Short and easy, for arrays, strings or also objects.
OP states he wanted to print to server-side terminal / standard output, not to html/js console.For Chrome there is an extension called Chrome Logger allowing to log PHP messages.
To enable the logging, you just need to save the 'ChromePhp.php' file in your project. Then it can be used like this:
The output may then look like this:
If you want write to the PHP log file, and not the JavaScript console you can use this:
error_log("This is logged only to the PHP log")
There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:
- See errors and exceptions in the Chrome JavaScript console and in the notification popups.
- Dump any type of variable.
- Execute PHP code remotely.
- Protect access by password.
- Group console logs by request.
- Jump to error file:line in your text editor.
- Copy error/debug data to the clipboard (for testers).
I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.
I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:
Usage is as follows:
If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.
Here is my solution, the good thing about this one is that you can pass as many params as you like.
Call it this way
Now you should be able to see output in your console, happy coding :)
I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!
Just click on one of the tabs at top right, or on the "click here" to expand/hide.
Notice the different "categories". You can click any array to expand/collapse it.
From the web page
- Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
- 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 JavaScript console (Chrome only), for Ajax scripts
I wrote some little modifications to the ChromePHP tool to allow seamless migration from FirePHP to Firebug for debugging via the console.
This article explains in clear easy steps
If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.
I might be late for a party, but I was looking for an implementation of logging function which:
- takes a variable number of comma separated arguments, just like javascript console.log() ,
- gives a formatted output (not just a serialized string),
- is distinguishable from a common javascript console.log() .
So the output looks like that:
(The snippet below is tested on php 7.2.11 . I'm not sure about its php backward compatibility. It can be an issue for javascript as well (in a term of old browsers), because it creates a trailing comma after console.log() arguments – which is not legal until ES 2017 .)
Clean, fast and simple without useless code:
Any of these two are working:
Here's a handy function. It is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP
Note, you can use tags as well by passing 'TAG-YourTag', and it will be applied until another tag is read, for example, 'TAG-YourNextTag'
NOTE: func_num_args() and func_num_args() are PHP functions for reading a dynamic number of input arguments, and allow this function to have infinitely many console.log requests from one function call.
Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.
CODE :
TESTS & USAGE :
Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.
EXPLANATION :
The function console($data, $is_error, $file, $fn) takes string or array as first argument and posts it on console using js inserts.
Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.
Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace() to fetch them for us.
Next function exceptions_to_console($svr, $str, $file, $ln) has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code) to provide more info on error.
NOTICE :
Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.
Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.
SUGGESTIONS :
First function console() threw some notices, so I've wrapped them within another function and called it using error control operator '@'. This can be avoided if you didn't mind the notices.
Читайте также: