Last active

GitHub PHP webhook to auto-pull on repo push

  • Download Gist
1 2 3 4 5 6 7 8 9
// Use in the "Post-Receive URLs" section of your GitHub repo.
if ( $_POST['payload'] ) {
shell_exec( 'cd /srv/www/git-repo/ && git reset --hard HEAD && git pull' );

This seems to be the bare minimum required to get a GitHub post-receive hook up and running with PHP on a webserver, to facilitate automatic site updates with group collaboration on a small static site.

I had to create a private/public key pair, without passphrase. The public key gets added in GitHub as a "deploy key" while the private key gets saved as /var/www/.ssh/id_rsa. I also did sudo touch /var/www/.ssh/known_hosts && sudo chmod www-data /var/www/.ssh/known_hosts, then ran sudo -u www-data git pull from the command line to update the known_hosts file.

(I think that's it)

Have any improvements? Let me know!

tried every which way and couldn't get this to work. script executed just fine from the command line using php script.php, but wouldn't work using service hooks. Oh well..

@sudo chmod www-data /var/www/.ssh/known_hosts" should be sudo chown www-data /var/www/.ssh/known_hosts.

Also make sure www-data have access to the files in /var/www/.ssh

The permission instructions were very helpfull, but the script doesn't work, so I made one that does:

Here is a similar project with a bit more advanced options:

I used suPHP to make the php webhook handler execute under my user instead of web server, hence no permissions problems and file ownership changes on pull. May sound scary but if the shell command is hard coded and suPHP is enabled only for that particular script (I can put it in a separate directory) it's pretty safe (feel free to call me out if that's still very bad %))

@jorijnsmit Interesting, a different approach to the problem! Thanks for sharing.

I'm concerned about git reset --hard HEAD... is it safe to do so? What if some tracked files are (accidentally) edited on a running server? This shouldn't happen, of course, but if it does, I think I'd rather have the change NOT propagate to the server instead of overwriting something.

just a little typo error.. it's receive not recieve.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.