Created
February 16, 2016 19:00
-
-
Save jpallari/0f3e7339bb23583572a6 to your computer and use it in GitHub Desktop.
Basic Github webhook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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