Home » Php » PHP dump $_REQUEST to file

PHP dump $_REQUEST to file

Posted by: admin April 23, 2020 Leave a comment


I want to dump request variables to a file for debugging. How’s this possible?

How to&Answers:
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);

Untested but should do the job, just change request.log to the file you want to write to.


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


Use serialize() function for dumping. Dump $_SERVER, $_COOKIE, $_POST and $_GET separately (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.

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 $_POST data, or limit server variables to those starting with HTTP_.


/* may be late but he can help others.
it's not my code, I get it from : 

            class DumpHTTPRequestToFile {
                public function execute($targetFile) {
                    $data = sprintf(
                        "%s %s %s\n\nHTTP headers:\n",
                    foreach ($this->getHeaderList() as $name => $value) {
                        $data .= $name . ': ' . $value . "\n";
                    $data .= "\nRequest body:\n";
                        $data . file_get_contents('php://input') . "\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");