Skip to content

Instantly share code, notes, and snippets.

@jkpl
Created February 16, 2016 19:00
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 jkpl/0f3e7339bb23583572a6 to your computer and use it in GitHub Desktop.
Save jkpl/0f3e7339bb23583572a6 to your computer and use it in GitHub Desktop.
Basic Github webhook
<?php
// Conf
$secret = 'mysecret';
$command = '/path/to/script.sh';
function fail($msg) {
http_response_code(400);
echo $msg;
exit(1);
}
function forbidden($msg) {
http_response_code(403);
echo 'forbidden access: ' . $msg;
exit(1);
}
// Request
$headers = getallheaders();
$event = $headers['X-Github-Event'];
$signature = $headers['X-Hub-Signature'];
list($algo, $hash) = explode('=', $signature, 2);
$payload = file_get_contents('php://input');
$payloadHash = hash_hmac($algo, $payload, $secret);
// Verify secret
if ($hash !== $payloadHash) forbidden('invalid secret');
// Verify request
if ($event === 'ping') {
echo 'pong';
exit(1);
}
if ($event !== 'push') fail('only accepting push events. got ' . $event . ' instead.');
// Execute command
$status = 0;
$out = "";
exec($command, $out, $status);
if ($status !== 0) {
error_log($out);
fail('error occurred while executing the command');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment