Skip to content

Instantly share code, notes, and snippets.

@andris9
Created June 22, 2022 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andris9/e1ad312ef25c46dd9397d2726995581a to your computer and use it in GitHub Desktop.
Save andris9/e1ad312ef25c46dd9397d2726995581a to your computer and use it in GitHub Desktop.
Webhook logging script
<?php
# This PHP script accepts all JSON POST bodies and stores these to a specified log file.
# You could then run `tail -f /var/log/whlog | jq` to tail pretty-printed JSON logs as these arrive
# must be writable for the PHP process
$log_filename = '/var/log/whlog';
if (!is_writable($log_filename)) {
http_response_code(500);
echo "Log file is not writable";
exit;
}
// validates a JSON formatted string
function is_valid_json($json_str)
{
if (!isset($json_str) || empty($json_str) || strlen($json_str) == 0) {
return false;
}
json_decode($json_str);
return json_last_error() == JSON_ERROR_NONE;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$post_body = file_get_contents("php://input");
if ($post_body) {
// Make sure the request content is always a valid JSON string
if (!is_valid_json($post_body)) {
$post_body = json_encode(array('error' => 'invalid_json', content => $post_body));
}
file_put_contents($log_filename,
// jq is not able to handle non-JSON lines so include request metadata
// also as part of the JSON entry
json_encode(array(
'time' => date('c'),
'remote_addr' => $_SERVER['REMOTE_ADDR'],
'content_type' => isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '',
'request' => json_decode($post_body),
)) . "\n",
FILE_APPEND);
}
}
echo "OK";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment