PHP 转储 $_REQUEST 到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3328189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP dump $_REQUEST to file
提问by Jamie Redmond
I want to dump request variables to a file for debugging. How's this possible?
我想将请求变量转储到文件中进行调试。这怎么可能?
回答by 46bit
<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Untested but should do the job, just change request.log to the file you want to write to.
未经测试但应该可以完成这项工作,只需将 request.log 更改为您要写入的文件。
回答by Peon
I think nowadays this method is easier and faster:
我认为现在这种方法更容易和更快:
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
回答by jmz
Use serialize()function for dumping. Dump $_SERVER, $_COOKIE, $_POSTand $_GETseparately (may go to the same file). If you're planning on debugging with the data it helps to know if the data was part of a POST request or a GET request.
使用serialize()功能进行倾销。转储$_SERVER,$_COOKIE,$_POST和$_GET分别(可以去到同一文件)。如果您计划对数据进行调试,那么了解数据是 POST 请求还是 GET 请求的一部分会很有帮助。
Dumping everything is good for debugging in development, but not so in production. If your application does not have many users, it can work in production too. If you anticipate many users, consider dumping just the $_POSTdata, or limit server variables to those starting with HTTP_.
转储一切有利于开发中的调试,但在生产中则不然。如果您的应用程序没有很多用户,它也可以在生产中工作。如果您预计会有很多用户,请考虑仅转储$_POST数据,或将服务器变量限制为以 HTTP_ 开头的变量。
回答by atifone
/* 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");

