-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_tracer.php
More file actions
71 lines (62 loc) · 1.71 KB
/
http_tracer.php
File metadata and controls
71 lines (62 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
// http tracer.
// tried implementing http-tracer from golang in php
// Start the tracer
function startTracer() {
ob_start();
}
// Stop the tracer
function stopTracer() {
$output = ob_get_contents();
ob_end_clean();
return $output;
}
// Get the HTTP request headers
function getRequestHeaders() {
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == 'HTTP_') {
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
}
return $headers;
}
// Get the HTTP response headers
function getResponseHeaders() {
$headers = array();
foreach (headers_list() as $header) {
list($key, $value) = explode(':', $header);
$headers[$key] = $value;
}
return $headers;
}
// Get the HTTP request body
function getRequestBody() {
return file_get_contents('php://input');
}
// Get the HTTP response body
function getResponseBody() {
return stopTracer();
}
// Log the HTTP request and response
function logRequestResponse() {
$request = array(
'method' => $_SERVER['REQUEST_METHOD'],
'uri' => $_SERVER['REQUEST_URI'],
'headers' => getRequestHeaders(),
'body' => getRequestBody()
);
$response = array(
'status' => http_response_code(),
'headers' => getResponseHeaders(),
'body' => getResponseBody()
);
// Log the request and response
error_log(json_encode(array('request' => $request, 'response' => $response)));
}
// Start the tracer
startTracer();
// Register a shutdown function to log the request and response
register_shutdown_function('logRequestResponse');