PHP将$ _REQUEST转储到文件中

Jam*_*ond 30 php

我想将请求变量转储到文件进行调试.这怎么可能?

46b*_*bit 54

<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

未经测试但应该完成这项工作,只需将request.log更改为您要写入的文件即可.

  • 完全没有必要关闭?>.实际上,最好的做法是在编写库/ etc(不是这里有关系)时省略它,以确保不会意外输出可能弄乱输出缓冲/头文件等的空格. (21认同)
  • 我个人喜欢`var_export($ var,true). (5认同)
  • @josh关闭?>没有必要,实际上它不是很好的做法.您可以在结束标记之后获得额外的空格,这可能会导致脚本出错 (3认同)

Peo*_*eon 20

我认为现在这种方法更简单,更快捷:

$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望附加到日志:`file_put_contents('request.log',$ req_dump,FILE_APPEND)` (5认同)

jmz*_*jmz 5

使用serialize()转储功能.转储$_SERVER,$_COOKIE,$_POST和$_GET分别(可以去到同一文件).如果您计划使用数据进行调试,则有助于了解数据是POST请求还是GET请求的一部分.

倾倒一切对于开发中的调试很有用,但在生产中则不然.如果您的应用程序没有很多用户,它也可以在生产中使用.如果您预计有许多用户,请考虑仅转储$_POST数据,或将服务器变量限制为以HTTP_开头的服务器变量.


小智 5

/* may be late but he can help others.
it's not my code, I get it from : 
https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
*/

            class DumpHTTPRequestToFile {
                public function execute($targetFile) {
                    $data = sprintf(
                        "%s %s %s\n\nHTTP headers:\n",
                        $_SERVER['REQUEST_METHOD'],
                        $_SERVER['REQUEST_URI'],
                        $_SERVER['SERVER_PROTOCOL']
                    );
                    foreach ($this->getHeaderList() as $name => $value) {
                        $data .= $name . ': ' . $value . "\n";
                    }
                    $data .= "\nRequest body:\n";
                    file_put_contents(
                        $targetFile,
                        $data . file_get_contents('php://input') . "\n"
                    );
                    echo("Done!\n\n");
                }
                private function getHeaderList() {
                    $headerList = [];
                    foreach ($_SERVER as $name => $value) {
                        if (preg_match('/^HTTP_/',$name)) {
                            // convert HTTP_HEADER_NAME to Header-Name
                            $name = strtr(substr($name,5),'_',' ');
                            $name = ucwords(strtolower($name));
                            $name = strtr($name,' ','-');
                            // add to list
                            $headerList[$name] = $value;
                        }
                    }
                    return $headerList;
                }
            }
            (new DumpHTTPRequestToFile)->execute('./dumprequest.txt');

            // add this line at the end to create a file for each request with timestamp

            $date = new DateTime();
            rename("dumprequest.txt", "dumprequest" . $date->format('Y-m-d H:i:sP') . ".txt");
Run Code Online (Sandbox Code Playgroud)