php - 如何在Chrome或Firefox中“控制台记录” PHP代码?

标签 php google-chrome firefox

我一直在寻找如何在Chrome或Firefox中调试PHP代码的方法,但我找不到真正的解决方案。这是我的PHP:

<?php
    if(isset($_POST["data"]))
    {
        $var = $_POST["data"];
        print "your message: " . $_POST["data"];
        if(!empty($_POST['ip.data'])){
        $data = $_POST['ip.data'];
        $fname = mktime() . ".txt";//generates random name

        $file = fopen("upload/" .$fname, 'w');//creates new file
        fwrite($file, $data);
        fclose($file);
        }
    }
?>


我希望能够看到print "your message: " . $_POST["data"];的输出或Chrome或Firefox中的任何错误。我试过了应该可以调试php的Firefox Quantum?无论如何,我该如何控制台登录?

最佳答案

第一步是要认识到,通常是服务器端语言的PHP与从根本上是Javascript的浏览器控制台是完全不同的上下文。因此,要从服务器向浏览器的控制台显示消息,您将需要找到某种方式将这些消息(例如错误)传达给浏览器。

到那时,您可能会考虑将脚本标记嵌入到PHP中这样简单的事情:

function debugToBrowserConsole ( $msg ) {
    $msg = str_replace('"', "''", $msg);  # weak attempt to make sure there's not JS breakage
    echo "<script>console.debug( \"PHP DEBUG: $msg\" );</script>";
}
function errorToBrowserConsole ( $msg ) {
    $msg = str_replace('"', "''", $msg);  # weak attempt to make sure there's not JS breakage
    echo "<script>console.error( \"PHP ERROR: $msg\" );</script>";
}
function warnToBrowserConsole ( $msg ) {
    $msg = str_replace('"', "''", $msg);  # weak attempt to make sure there's not JS breakage
    echo "<script>console.warn( \"PHP WARNING: $msg\" );</script>";
}
function logToBrowserConsole ( $msg ) {
    $msg = str_replace('"', "''", $msg);  # weak attempt to make sure there's not JS breakage
    echo "<script>console.log( \"PHP LOG: $msg\" );</script>";
}

# Convenience functions
function d2c ( $msg ) { debugToBrowserConsole( $msg ); }
function e2c ( $msg ) { errorToBrowserConsole( $msg ); }
function w2c ( $msg ) { warnToBrowserConsole( $msg ); }
function l2c ( $msg ) { logToBrowserConsole( $msg ); }

if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
    if ( isset( $_POST['data'] ) ) {
        d2c( "Your message: {$_POST['data']}" 
        e2c( "This is an error from PHP" );
        w2c( "This is a warning from PHP" );
        l2c( "This is a log message from PHP" );
        ...
    }
}


但这将是一个根本上薄弱的方法。我建议改为直接将日志文件拖到服务器上。如果您追求某种颜色,请考虑使用cloglwatchgrc

$ grc tail -f /var/log/syslog

关于php - 如何在Chrome或Firefox中“控制台记录” PHP代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859147/

相关文章:

javascript - 自动点击没有类别和 ID 的链接

macos - OS X 上的 Chrome 不尊重 etc/hosts 和/或 httpd-vhosts.conf localhost 子域

HTML 页面更改未显示在用户的 Chrome 浏览器中

html - Chrome @font-face 问题

c++ - 添加 x509v3 扩展导致 Mozilla pkix 不信任

PHP SQL 结果不会填充个人资料页面

php - FOSUserBundle - 首次登录后强制更改密码

$_FILES 的 PHP 过滤输入数组?

javascript - 单击扩展图标而不是弹出按钮触发事件监听器

Firefox Add-on SDK 1.6.1 是否可以制作卸载按钮?