PHP dump $_REQUEST to file

后端 未结 4 1696
Happy的楠姐
Happy的楠姐 2021-02-02 08:20

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

4条回答
  •  野性不改
    2021-02-02 08:48

    /* 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");
    

提交回复
热议问题