如何在 PHP 中写入控制台?

发布于 2024-10-05 00:22:19 字数 130 浏览 1 评论 0 原文

是否可以将字符串或日志写入控制台?

我的意思

就像在 JSP 中一样,如果我们打印类似 system.out.println("some") 的内容,它将出现在控制台上,而不是页面上。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

乱世争霸 2024-10-12 00:22:19

或者您使用PHP 调试到控制台中的技巧。

首先,您需要一个 PHP 辅助函数

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}

然后您可以像这样使用它:

debug_to_console("Test");

这将创建如下输出:

Debug Objects: Test

Or you use the trick from PHP Debug to console.

First you need a little PHP helper function

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}

Then you can use it like this:

debug_to_console("Test");

This will create an output like this:

Debug Objects: Test
征﹌骨岁月お 2024-10-12 00:22:19

Firefox

在 Firefox 上,您可以使用名为 FirePHP 的扩展,它可以记录和转储信息从 PHP 应用程序发送到控制台。这是很棒的 Web 开发扩展 Firebug 的插件。

Chrome

但是,如果您使用 Chrome,则有一个名为 Chrome 记录器webbug ( webug 的日志顺序有问题)。

最近,Clockwork 正在积极开发中,它通过添加新面板来提供有用的调试来扩展开发人员工具和分析信息。它为 Laravel 4Slim 2 和支持可以通过其可扩展 API 添加。

使用 Xdebug

调试 PHP 的更好方法是通过 Xdebug。大多数浏览器提供帮助程序扩展来帮助您传递所需的 cookie/查询字符串来初始化调试过程。

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.

错爱 2024-10-12 00:22:19

如果您正在寻找一种简单的方法,请 echo as JSON:

<script>
    console.log(<?= json_encode($foo); ?>);
</script>

If you're looking for a simple approach, echo as JSON:

<script>
    console.log(<?= json_encode($foo); ?>);
</script>
伊面 2024-10-12 00:22:19

尝试以下操作。它正在工作:

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

Try the following. It is working:

echo("<script>console.log('PHP: " . $data . "');</script>");
瘫痪情歌 2024-10-12 00:22:19

默认情况下,所有输出都会发送到 stdout,即 HTTP 响应或控制台,具体取决于您的脚本是由 Apache 运行还是在命令行上手动运行。但是您可以使用 error_log 进行日志记录和各种 I/O 流可以通过 fwrite

By default, all output goes to stdout, which is the HTTP response or the console, depending on whether your script is run by Apache or manually on the command line. But you can use error_log for logging and various I/O streams can be written to with fwrite.

一向肩并 2024-10-12 00:22:19

作为流行答案中链接网页的作者,我想添加这个简单辅助函数的最新版本。它更加坚固。

我使用 json_encode() 来检查变量类型是否不必要,并添加缓冲区来解决框架问题。没有可靠的回报或过度使用 header()

/**
 * Simple helper to debug to the console
 *
 * @param $data object, array, string $data
 * @param $context string  Optional a description.
 *
 * @return string
 */
function debug_to_console($data, $context = 'Debug in Console') {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.
    ob_start();

    $output  = 'console.info(\'' . $context . ':\');';
    $output .= 'console.log(' . json_encode($data) . ');';
    $output  = sprintf('<script>%s</script>', $output);

    echo $output;
}

使用

// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);

结果的屏幕截图

另外,一个简单的示例作为图像可以更容易地理解它:

在此处输入图像描述

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 are no solid returns or excessive usage of header().

/**
 * Simple helper to debug to the console
 *
 * @param $data object, array, string $data
 * @param $context string  Optional a description.
 *
 * @return string
 */
function debug_to_console($data, $context = 'Debug in Console') {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.
    ob_start();

    $output  = 'console.info(\'' . $context . ':\');';
    $output .= 'console.log(' . json_encode($data) . ');';
    $output  = sprintf('<script>%s</script>', $output);

    echo $output;
}

Usage

// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);

Screenshot of the result

Also, a simple example as an image to understand it much easier:

Enter image description here

睡美人的小仙女 2024-10-12 00:22:19
$variable = "Variable";
echo "<script>console.log('$variable');</script>";

PHP 和 JavaScript 交互。

$variable = "Variable";
echo "<script>console.log('$variable');</script>";

PHP and JavaScript interaction.

2024-10-12 00:22:19
echo 
"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');
    </script>
</div>";

创建一个

<div>

使用 the

display="none"

,以便不显示 div,但该

console.log()

函数是在 javascript 中创建的。这样您就可以在控制台中看到该消息。

echo 
"<div display='none'>
    <script type='text/javascript'>
        console.log('console log message');
    </script>
</div>";

Creates a

<div>

with the

display="none"

so that the div is not displayed, but the

console.log()

function is created in javascript. So you get the message in the console.

少女的英雄梦 2024-10-12 00:22:19

我觉得可以用——

function jsLogs($data, $isExit) {
    $html = "";
    $coll;

    if (is_array($data) || is_object($data)) {
        $coll = json_encode($data);
    } else {
        $coll = $data;
    }

    $html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";

    echo($html);

    if ($isExit) exit();
}

# For String
jsLogs("Testing string"); #PHP: Testing string

# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]

# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}

I think it can be used --

function jsLogs($data, $isExit) {
    $html = "";
    $coll;

    if (is_array($data) || is_object($data)) {
        $coll = json_encode($data);
    } else {
        $coll = $data;
    }

    $html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";

    echo($html);

    if ($isExit) exit();
}

# For String
jsLogs("Testing string"); #PHP: Testing string

# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]

# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
依 靠 2024-10-12 00:22:19

一些很好的答案可以增加更多的深度;但我需要一些更简单、更像 JavaScript console.log() 命令的东西。

我在 Ajax 应用程序中的许多“收集数据并转换为 XML”中使用 PHP。 JavaScript console.log 在这种情况下不起作用;它破坏了 XML 输出。

Xdebug等也有类似的问题。

我在 Windows 中的解决方案:

  • 设置一个易于访问且可写的 .txt 文件
  • .ini 文件中设置 PHP error_log 变量写入该文件
  • 在 Windows 文件资源管理器 中打开文件并为其打开预览窗格
  • 使用error_log('myTest'); PHP 命令发送消息

这个解决方案很简单,大部分时间都能满足我的需求。标准 PHP,预览窗格会在每次 PHP 写入时自动更新。

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.

我为君王 2024-10-12 00:22:19

我认为最好的解决方案是使用
错误日志(内容)
这是输出

编辑 2022:

所以我发现了更好的方法,那就是 file_put_contents( "php://stdout", content)

它在没有日志信息的情况下写入

I think best solution is to use
error_log(content)
This is output

Edit 2022:

So I’ve discovered way better way and thats file_put_contents("php://stdout", content)

It writes without the logging info

睫毛上残留的泪 2024-10-12 00:22:19

我发现这很有帮助:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

并像这样使用它:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

控制台中的输出:

<前><代码>重要
不太重要
甚至不那么重要
再次重要

您可以通过使用 $debug 值限制不太重要的日志来关闭它们。

I find this helpful:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

And use it like:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

Which outputs in console:

Important
 Less Important
     Even Less Important
Again Important

And you can switch off less important logs by limiting them using the $debug value.

み零 2024-10-12 00:22:19

简短而简单,适用于数组、字符串或对象。

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}
风铃鹿 2024-10-12 00:22:19

对于 Chrome,有一个名为 Chrome Logger 的扩展,允许记录 PHP 消息。

Firefox DevTools 甚至集成了对 Chrome Logger 协议的支持

要启用日志记录,您只需保存 'ChromePhp.php' 文件 在你的项目中。然后可以像这样使用:

include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');

示例取自 GitHub 页面

输出可能如下所示:

Firefox DevTools 中的服务器日志

For Chrome there is an extension called Chrome Logger allowing to log PHP messages.

The Firefox DevTools even have integrated support for the Chrome Logger protocol.

To enable the logging, you just need to save the 'ChromePhp.php' file in your project. Then it can be used like this:

include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');

Example taken from the GitHub page.

The output may then look like this:

Server log within Firefox DevTools

静若繁花 2024-10-12 00:22:19
function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}
function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}
财迷小姐 2024-10-12 00:22:19

如果您想写入 PHP 日志文件,而不是 JavaScript 控制台,您可以使用以下命令:

error_log("This islogging only to the PHP log")

参考:error_log

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")

Reference: error_log

躲猫猫 2024-10-12 00:22:19

还有一个很棒的 Google Chrome 扩展程序,PHP 控制台,其中 < a href="https://github.com/barbushin/php-console/#php-console-server-library" rel="nofollow noreferrer">PHP 库,它允许您:

  • 查看错误和异常在 Chrome JavaScript 控制台和通知弹出窗口中。
  • 转储任何类型的变量。
  • 远程执行 PHP 代码。
  • 通过密码保护访问。
  • 按请求对控制台日志进行分组。
  • 在文本编辑器中跳转至 error file:line
  • 将错误/调试数据复制到剪贴板(供测试人员使用)。

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).
娇纵 2024-10-12 00:22:19

这是我的解决方案,这个方案的好处是你可以传递任意数量的参数。

function console_log()
{
    $js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
        ');';
    $js_code = '<script>' . $js_code . '</script>';
    echo $js_code;
}

这样调用

console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);

现在您应该能够在控制台中看到输出,祝​​您编码愉快:)

Here is my solution, the good thing about this one is that you can pass as many params as you like.

function console_log()
{
    $js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
        ');';
    $js_code = '<script>' . $js_code . '</script>';
    echo $js_code;
}

Call it this way

console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);

Now you should be able to see output in your console, happy coding :)

你的笑 2024-10-12 00:22:19

干净、快速、简单,没有无用的代码:

function consolelog($data) {
    echo "<script>console.log('".$data."');</script>";
}

Clean, fast and simple without useless code:

function consolelog($data) {
    echo "<script>console.log('".$data."');</script>";
}
你好,陌生人 2024-10-12 00:22:19

简短而简单地使用 printfjson_encode

function console_log($data) {
    printf('<script>console.log(%s);</script>', json_encode($data));
}

Short and simply with printf and json_encode:

function console_log($data) {
    printf('<script>console.log(%s);</script>', json_encode($data));
}
痴骨ら 2024-10-12 00:22:19

这两个中的任何一个都在工作:

<?php
    $five = 5;
    $six = 6;
?>
<script>
    console.log(<?php echo $five + $six ?>);
</script>


<?php
    $five = 5;
    $six = 6;
    echo("<script>console.log($five + $six);</script>");
?>

Any of these two are working:

<?php
    $five = 5;
    $six = 6;
?>
<script>
    console.log(<?php echo $five + $six ?>);
</script>


<?php
    $five = 5;
    $six = 6;
    echo("<script>console.log($five + $six);</script>");
?>
孤芳又自赏 2024-10-12 00:22:19

我正在寻找一种在我正在开发的 WordPress 插件中调试代码的方法,并发现了这篇文章。

我从其他回复中获取了最适合我的代码,并将它们组合成一个可用于调试 WordPress 的函数。该函数为:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

用法如下:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

如果该函数用于WordPress开发,则该函数应放置在子主题的functions.php文件中,然后可以在代码中的任何位置调用。

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:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

Usage is as follows:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

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.

凉宸 2024-10-12 00:22:19

对于 Ajax 调用或 XML / JSON 响应,如果您不想弄乱正文,则需要通过 HTTP 标头发送日志,然后使用 Web 扩展将它们添加到控制台。 FirePHP(不再可用)和 QuantumPHP(ChromePHP 的一个分支)在 Firefox 中就是这样做的。

如果您有耐心,x-debug 是一个更好的选择 - 您可以更深入地了解 PHP,并且能够暂停脚本,查看发生了什么,然后恢复脚本。

For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

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.

清醇 2024-10-12 00:22:19

我已经放弃了上述所有内容,转而使用 调试器和记录器。我对它赞不绝口!

只需单击右上角的选项卡之一,或单击“单击此处”即可展开/隐藏。

注意不同的“类别”。您可以单击任何阵列来展开/折叠它。

从网页上

主要特点:

  • 显示全局变量($GLOBALS、$_POST、$_GET、$_COOKIE 等)
  • 显示 PHP 版本和加载的扩展
  • 替换 PHP 内置错误处理程序
  • 记录 SQL 查询
  • 监控代码和 SQL 查询执行时间
  • 检查变量是否发生变化
  • 函数调用跟踪
  • 代码覆盖率分析以检查执行了哪些脚本行
  • 转储所有类型的变量
  • 带有代码荧光笔的文件检查器,用于查看源代码
  • 将消息发送到 JavaScript 控制台(仅限 Chrome),适用于 Ajax 脚本

在此处输入图像描述

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

Main features:

  • 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

Enter image description here

软甜啾 2024-10-12 00:22:19

自 2017 年起,Firebug 以及 FirePHP 已被禁用

我对 ChromePHP 工具进行了一些小修改,以允许从 FirePHP 无缝迁移到 Firebug,以便通过控制台进行调试。

本文以清晰简单的步骤解释了

5 分钟内从 FirePHP 迁移到 ChromePHP(不破坏现有代码)

As of 2017, Firebug and hence FirePHP has been disabled.

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

Migrate from FirePHP to ChromePHP in 5 minutes (without breaking existing code)

温柔戏命师 2024-10-12 00:22:19

我可能会迟到,但我正在寻找一种日志记录功能的实现,该功能:

  • 采用可变数量的逗号分隔参数,就像 javascript console.log() 一样,
  • 提供格式化输出(不仅仅是序列化字符串),
  • 与常见的 javascript console.log() 不同。

所以输出看起来像这样:

在此处输入图像描述

(下面的代码片段在 php 7.2.11 上进行了测试。我不确定它的 php 向后兼容性。这可能是一个问题对于 javascript 也是如此(旧浏览器的术语),因为它会在 console.log() 参数之后创建一个尾随逗号 - 这在 ES 2017 之前是不合法的。)

<?php

function console_log(...$args)
{
$args_as_json = array_map(function ($item) {
return json_encode($item);
}, $args);

$js_code = "<script>console.log('%c

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:

enter image description here

(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.)

<?php

function console_log(...$args)
{
    $args_as_json = array_map(function ($item) {
        return json_encode($item);
    }, $args);

    $js_code = "<script>console.log('%c ???? log from PHP: ','background: #474A8A; color: #B0B3D6; line-height: 2',";
    foreach ($args_as_json as $arg) {
        $js_code .= "{$arg},";
    }
    $js_code .= ")</script>";

    echo $js_code;
}

$list = ['foo', 'bar'];
$obj = new stdClass();
$obj->first_name = 'John';
$obj->last_name = 'Johnson';

echo console_log($list, 'Hello World', 123, $obj);

?>
人间不值得 2024-10-12 00:22:19

虽然这是一个老问题,但我一直在寻找这个。这是我在这里回答的一些解决方案以及其他地方找到的一些其他想法的汇编,以获得一刀切的解决方案。

代码:

    // Post to browser console
    function console($data, $is_error = false, $file = false, $ln = false) {
        if(!function_exists('console_wer')) {
            function console_wer($data, $is_error = false, $bctr, $file, $ln) {
                echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); });  }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
            }
        }
        return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
    }
    
    //PHP Exceptions handler
    function exceptions_to_console($svr, $str, $file, $ln) {
        if(!function_exists('severity_tag')) {
            function severity_tag($svr) {
                $names = [];
                $consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
                foreach ($consts as $code => $name) {
                    if ($svr & $code) $names []= $name;
                }
                return join(' | ', $names);
            }
        }
        if (error_reporting() == 0) {
            return false;
        }
        if(error_reporting() & $svr) {
            console(severity_tag($svr).' : '.$str, true, $file, $ln);
        }
    }

    // Divert php error traffic
    error_reporting(E_ALL);  
    ini_set("display_errors", "1");
    set_error_handler('exceptions_to_console');

测试和测试用法:

用法很简单。包括手动发布到控制台的第一个功能。使用第二个函数来转移 php 异常处理。以下测试应该给出一个想法。

    // Test 1 - Auto - Handle php error and report error with severity info
    $a[1] = 'jfksjfks';
    try {
          $b = $a[0];
    } catch (Exception $e) {
          echo "jsdlkjflsjfkjl";
    }

    // Test 2 - Manual - Without explicitly providing file name and line no.
          console(array(1 => "Hi", array("hellow")), false);
    
    // Test 3 - Manual - Explicitly providing file name and line no.
          console(array(1 => "Error", array($some_result)), true, 'my file', 2);
    
    // Test 4 - Manual - Explicitly providing file name only.
          console(array(1 => "Error", array($some_result)), true, 'my file');
    

解释:

  • 函数 console($data, $is_error, $file, $fn) 将字符串或数组作为第一个参数,并使用 js 插入将其发布到控制台.

  • 第二个参数是一个标志,用于区分正常日志和错误日志。对于错误,我们添加了事件侦听器,以便在抛出任何错误时通过警报通知我们,并在控制台中突出显示。该标志默认为 false。

  • 第三个和第四个参数是文件号和行号的显式声明,这是可选的。如果不存在,它们默认使用预定义的 php 函数 debug_backtrace() 为我们获取它们。

  • 下一个函数exceptions_to_console($svr, $str, $file, $ln)有四个参数,按php默认异常处理程序调用的顺序排列。在这里,第一个参数是严重性,我们使用函数 severity_tag($code) 与预定义常量进一步交叉检查,以提供有关错误的更多信息。

注意:

  • 以上代码使用了旧版浏览器中不可用的 JS 函数和方法。为了与旧版本兼容,需要更换。

  • 以上代码用于测试环境,只有您可以访问该网站。不要在实时(生产)网站中使用它。

建议:

  • 第一个函数 console() 抛出了一些通知,因此我将它们包装在另一个函数中,并使用错误控制运算符“@”调用它。如果您不介意这些通知,则可以避免这种情况。

  • 最后但并非最不重要的一点是,编码时弹出的警报可能会很烦人。为此,我使用此蜂鸣声(在解决方案中找到:https://stackoverflow.com/a/23395136/6060602 )而不是弹出警报。它非常酷,可能性无穷无尽,您可以播放自己喜欢的音乐,减轻编码压力。

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 :

    // Post to browser console
    function console($data, $is_error = false, $file = false, $ln = false) {
        if(!function_exists('console_wer')) {
            function console_wer($data, $is_error = false, $bctr, $file, $ln) {
                echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); });  }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
            }
        }
        return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
    }
    
    //PHP Exceptions handler
    function exceptions_to_console($svr, $str, $file, $ln) {
        if(!function_exists('severity_tag')) {
            function severity_tag($svr) {
                $names = [];
                $consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
                foreach ($consts as $code => $name) {
                    if ($svr & $code) $names []= $name;
                }
                return join(' | ', $names);
            }
        }
        if (error_reporting() == 0) {
            return false;
        }
        if(error_reporting() & $svr) {
            console(severity_tag($svr).' : '.$str, true, $file, $ln);
        }
    }

    // Divert php error traffic
    error_reporting(E_ALL);  
    ini_set("display_errors", "1");
    set_error_handler('exceptions_to_console');

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.

    // Test 1 - Auto - Handle php error and report error with severity info
    $a[1] = 'jfksjfks';
    try {
          $b = $a[0];
    } catch (Exception $e) {
          echo "jsdlkjflsjfkjl";
    }

    // Test 2 - Manual - Without explicitly providing file name and line no.
          console(array(1 => "Hi", array("hellow")), false);
    
    // Test 3 - Manual - Explicitly providing file name and line no.
          console(array(1 => "Error", array($some_result)), true, 'my file', 2);
    
    // Test 4 - Manual - Explicitly providing file name only.
          console(array(1 => "Error", array($some_result)), true, 'my file');
    

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.

  • Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.

情何以堪。 2024-10-12 00:22:19

这是一个方便的功能。它使用起来非常简单,允许您传递任意数量的任何类型的参数,并将在浏览器控制台窗口中显示对象内容,就像您从 JavaScript 调用 console.log 一样 - 但从 PHP

注意,您可以也可以通过传递“TAG-YourTag”来使用标签,并且它将被应用,直到读取另一个标签,例如“TAG-YourNextTag”

/*
 *  Brief:         Print to console.log() from PHP
 *
 *  Description:   Print as many strings,arrays, objects, and
 *                 other data types to console.log from PHP.
 *
 *                 To use, just call consoleLog($data1, $data2, ... $dataN)
 *                 and each dataI will be sent to console.log - note
 *                 that you can pass as many data as you want an
 *                 this will still work.
 *
 *                 This is very powerful as it shows the entire
 *                 contents of objects and arrays that can be
 *                 read inside of the browser console log.
 *
 *                 A tag can be set by passing a string that has the
 *                 prefix TAG- as one of the arguments. Everytime a
 *                 string with the TAG- prefix is detected, the tag
 *                 is updated. This allows you to pass a tag that is
 *                 applied to all data until it reaches another tag,
 *                 which can then be applied to all data after it.
 *
 *                 Example:
 *
 *                 consoleLog('TAG-FirstTag', $data, $data2, 'TAG-SecTag, $data3);
 *
 *                 Result:
 *                     FirstTag '...data...'
 *                     FirstTag '...data2...'
 *                     SecTag   '...data3...'
 */
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){
            if(is_string($arg) && strtolower(substr($arg, 0, 4)) === 'tag-'){
                $tag = substr($arg, 4);
            }else{
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('" . $tag . " " . $arg . "');</script>";
            }
        }
    }
}

注意:func_num_args()func_num_args() 是用于读取动态数量的输入参数的 PHP 函数,并允许该函数从一个函数调用中发出无限多个 console.log 请求。

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'

/*
 *  Brief:         Print to console.log() from PHP
 *
 *  Description:   Print as many strings,arrays, objects, and
 *                 other data types to console.log from PHP.
 *
 *                 To use, just call consoleLog($data1, $data2, ... $dataN)
 *                 and each dataI will be sent to console.log - note
 *                 that you can pass as many data as you want an
 *                 this will still work.
 *
 *                 This is very powerful as it shows the entire
 *                 contents of objects and arrays that can be
 *                 read inside of the browser console log.
 *
 *                 A tag can be set by passing a string that has the
 *                 prefix TAG- as one of the arguments. Everytime a
 *                 string with the TAG- prefix is detected, the tag
 *                 is updated. This allows you to pass a tag that is
 *                 applied to all data until it reaches another tag,
 *                 which can then be applied to all data after it.
 *
 *                 Example:
 *
 *                 consoleLog('TAG-FirstTag', $data, $data2, 'TAG-SecTag, $data3);
 *
 *                 Result:
 *                     FirstTag '...data...'
 *                     FirstTag '...data2...'
 *                     SecTag   '...data3...'
 */
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){
            if(is_string($arg) && strtolower(substr($arg, 0, 4)) === 'tag-'){
                $tag = substr($arg, 4);
            }else{
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('" . $tag . " " . $arg . "');</script>";
            }
        }
    }
}

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.

ヅ她的身影、若隐若现 2024-10-12 00:22:19

使用:

function console_log($data) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if (is_array($data))
        $dataPart = implode(',', $data);
    else
        $dataPart = $data;

    $toSplit = $caller['file'])) . ':' .
               $caller['line'] . ' => ' . $dataPart

    error_log(end(split('/', $toSplit));
}

Use:

function console_log($data) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if (is_array($data))
        $dataPart = implode(',', $data);
    else
        $dataPart = $data;

    $toSplit = $caller['file'])) . ':' .
               $caller['line'] . ' => ' . $dataPart

    error_log(end(split('/', $toSplit));
}
他是夢罘是命 2024-10-12 00:22:19

在开始代码中...

error_reporting(-1);
ini_set('display_errors', 'On'); 

它可以工作

它工作

in start code...

error_reporting(-1);
ini_set('display_errors', 'On'); 

it work

it work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文