Skip to content

Instantly share code, notes, and snippets.

@bensandee
Forked from mrjones-plip/_readme.md
Created January 17, 2021 05:25
Show Gist options
  • Save bensandee/4c59fc4032f7de2042edaaa3094832a7 to your computer and use it in GitHub Desktop.
Save bensandee/4c59fc4032f7de2042edaaa3094832a7 to your computer and use it in GitHub Desktop.
PHP Endpoint for Github Webhook URLs

PHP Endpoint for Github Webhook URLs

If you love deploying websites using Github, but for some reason want to use your own server, this script might be exactly what you need.

  1. Put github.php somewhere on your PHP-enabled web server, and make it accessible for the outside world. Let's say for now the script lives on http://example.com/github.php

  2. Somewhere on your server you need to have an update script that pulls your site from Github. If you're lucky, git is available on your server and you just need to run cd myrepo; git pull. If not, you might as well download the entire repository as zip, unpack it, etc. Make sure that it is executable. Let's say the script lives on /path/to/update/script.sh.

  3. Put config.json next to github.php and update it according to your needs.

    If you want email notification (yes, you want!), enter your email address to email.to. The emails will also be sent to the email of the Github user who pushed to the repository. To help yourself recognizing where these strange commit emails are comming from, you should set email.from to something meaningful like [email protected].

    You can use it for several repositories or branches at the same time by adding more entries to the endpoints list. For each endpoint you need to set endpoint.repo to "username/reponame". You can configure endpoints for different branches, for instance if you store your website in gh-pages branch or use different branches for development/production etc.

    Set endpoint.run to the path of your update script, e.g. /path/to/update/script.sh.

    For clarity, describe what happened after the update script has been executed under endpoint.action. Usually that's something like "Your website XY has been updated.". It will be used as subject in notification emails. This is especially helpful if you have multiple endpoints.

    The email will also contain the output of your update script and all the messages of the pushed commits.

    Set endpoint.secret to a really good secret

  4. On the settings page of your Github repository, go to Service Hooks > WebHook URLs and enter the public url of your github.php, e.g. http://example.com/github.php. On the same page you see a list of IP addresses Github sends the requests from. Make sure they're the same as defined below. Be sure set the secret on this page to the same value of endpoint.run above.

  5. If you don't want everybody to see your config.json, either prevent access using .htaccess or the like, or move it to a secure location on your server. If you move it, make sure the PHP script knows where to find it.

And that's it.

{
"email": {
"from": "[email protected]",
"to": "[email protected]"
},
"endpoints": [
{
"repo": "user/repository",
"branch": "master",
"action": "something has been changed on the server",
"run": "/path/to/update_script.sh",
"secret": "secret_here!"
}
]
}
<?php
/*
* Endpoint for Github Webhook URLs
*
* see: https://help.github.com/articles/post-receive-hooks
* Originally from : https://gist.github.com/gka/4627519
* This version: https://gist.github.com/Ths2-9Y-LqJt6/e0ce87ef6eef1253c6c8c7cb91cd7bc6
*/
// script errors will be send to this email:
$error_mail = "[email protected]";
function run() {
global $rawInput;
// read config.json
$config_filename = 'config.json';
if (!file_exists($config_filename)) {
throw new Exception("Can't find ".$config_filename);
}
$config = json_decode(file_get_contents($config_filename), true);
$postBody = $_POST['payload'];
$payload = json_decode($postBody);
if (isset($config['email'])) {
$headers = 'From: '.$config['email']['from']."\r\n";
$headers .= 'CC: ' . $payload->pusher->email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
}
// check if the request comes from github server
foreach ($config['endpoints'] as $endpoint) {
// thanks to https://gist.github.com/milo/daed6e958ea534e4eba3 for the php://input tip!
$sha = 'sha1=' . hash_hmac( 'sha1', file_get_contents('php://input'), $endpoint['secret'] );
if( $sha === $_SERVER[ 'HTTP_X_HUB_SIGNATURE' ]){
// check if the push came from the right repository and branch
if ($payload->repository->url == 'https://github.com/' . $endpoint['repo']
&& $payload->ref == 'refs/heads/' . $endpoint['branch']) {
// execute update script, and record its output
ob_start();
passthru($endpoint['run']);
$output = ob_get_clean();
// prepare and send the notification email
if (isset($config['email'])) {
// send mail to someone, and the github user who pushed the commit
$body = '<p>The Github user <a href="https://github.com/'
. $payload->pusher->name .'">@' . $payload->pusher->name . '</a>'
. ' has pushed to ' . $payload->repository->url
. ' and consequently, ' . $endpoint['action']
. '.</p>';
$body .= '<p>Here\'s a brief list of what has been changed:</p>';
$body .= '<ul>';
foreach ($payload->commits as $commit) {
$body .= '<li>'.$commit->message.'<br />';
$body .= '<small style="color:#999">added: <b>'.count($commit->added)
.'</b> &nbsp; modified: <b>'.count($commit->modified)
.'</b> &nbsp; removed: <b>'.count($commit->removed)
.'</b> &nbsp; <a href="' . $commit->url
. '">read more</a></small></li>';
}
$body .= '</ul>';
$body .= '<p>What follows is the output of the script:</p><pre>';
$body .= $output. '</pre>';
$body .= '<p>Cheers, <br/>Github Webhook Endpoint</p>';
mail($config['email']['to'], $endpoint['action'], $body, $headers);
}
error_log("github.php: ACTION=\"{$endpoint['action']}\" PUSHER=\"{$payload->pusher->name}\" ");
return true;
}
} else {
error_log('github.php: bad secret secret="' . $endpoint['secret'] . '" hash="' . $sha . '" header="' . $_SERVER['HTTP_X_HUB_SIGNATURE']. '"');
}
}
}
try {
if (!isset($_POST['payload'])) {
error_log('$_POST[\'payload\'] not set');
echo "Works fine.";
} else {
run();
}
} catch ( Exception $e ) {
$msg = $e->getMessage();
error_log('github.php: error="' . $msg . '"');
mail($error_mail, $msg, ''.$e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment