ryoakg
7/7/2016 - 9:59 AM

HTTPリクエストを評価する際に見る必要があるかもしれないデータ

HTTPリクエストを評価する際に見る必要があるかもしれないデータ

<?php
if (PHP_SAPI === 'cli'){
    echo "Usage:" . PHP_EOL . PHP_EOL;
    echo "#1 run a server:" . PHP_EOL;
    echo "  php -S localhost:<port> http-request-analyzer.php" . PHP_EOL . PHP_EOL;

    echo <<<EOT
#2 Request with cURL like the following:
  curl http://localhost:8080/"
  curl http://localhost:8080/?a=1"
  curl -H aaa:123 -X POST -d foo=bar -d bbb=999 'http://localhost:8080/?a=1'"
  curl -H aaa:123 -X DELETE -d foo=bar -d bbb=999 'http://localhost:8080/?a=1'"
  curl -H "Content-type: application/json" -X POST -d '{"name":"foo"}' 'http://localhost:8080/?a=1'
  curl -H "Content-type: application/xml" -X POST -d "<?xml version='1.0' standalone='yes'?><movies><movie><title>Foo</title></movie></movies>" 'http://localhost:8080/?a=1'
EOT
        ;
    exit;
}

function term_dump($x){
    ob_start();
    var_dump($x);
    error_log(ob_get_clean(), 4);
}

function as_www_form_encoded($str){
    parse_str($str, $a);
    return $a;
}

function url(){
    $r = parse_url($_SERVER['REQUEST_URI']);
    $r['query'] = as_www_form_encoded(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY));
    return $r;
}

function request_body(){
    $t = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : $_SERVER['HTTP_CONTENT_TYPE'];
    $c = file_get_contents('php://input');
    if ($t === 'x-www-form-urlencoded'){
        return as_www_form_encoded($c);
    } elseif ($t === 'application/json'){
        return json_decode($c);
    } elseif ($t === 'application/xml' || $t === 'text/xml'){
        return simplexml_load_string($c);
    } else {
        return $c;
    }
}

term_dump(array(
    // https://tools.ietf.org/html/rfc7231
    // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
    //   OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // https://tools.ietf.org/html/rfc5789
    //   PATCH
    'method' => $_SERVER['REQUEST_METHOD'],
    'header' => getallheaders(),
    'cookie' => $_COOKIE,
    // 'session' => $_SESSION,
    'url' => url(),
    'body' => request_body(),
));