Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable the request log, even when a router script is used for the PHP built-in web server

PHP's built in web server allows "router scripts" to be used, allowing for rewriting URLs internally.

The problem with such a router script is the fact that whenever it actually handles a file instead of letting PHP handle it, this causes the request log output for that request to be suppressed. For example, consider the following script:

<?php
if (preg_match('/^\/(js|css)/', $_SERVER['REQUEST_URI']) === 1) {
  return false;
}
else {
  echo 'hello world!'
}

This causes requests for /js/* and /css/* to be logged on the console; whereas requests for any other URLs simply skip logging the request.

How can I enable logging of all requests to the console?

like image 825
user2064000 Avatar asked Aug 07 '16 16:08

user2064000


1 Answers

router.php :

if (preg_match('/^\/(js|css)/', $_SERVER['REQUEST_URI']) === 1) {
    return false;
}
else {
    $stdErr = fopen("php://stderr",'w+');
    fwrite($stdErr, 'LogRequest:'.$_SERVER['REQUEST_URI']."\n");
    echo 'hello world!1';
}

Server start: php -S localhost:8000 router.php 2>&1

To log response headers:

if (preg_match('/^\/(js|css)/', $_SERVER['REQUEST_URI']) === 1) {
    return false;
}
else {
    ob_start() 
    $stdErr = fopen("php://stderr",'w+');
    fwrite($stdErr, 'Request:'.json_encode($_SERVER)."\n");
    try {
      echo 'hello world!1';
    } catch (\Exception $e) {
        http_response_code(500);
    }
    $response = ob_get_clean();
    fwrite($stdErr, 'Response:'.json_encode([ http_response_code(),headers_list() ])."\n");
    echo $response;
}
like image 99
cske Avatar answered Oct 10 '22 01:10

cske