Gitlab Webhook in PHP

I started using Gitlab a while ago, and wanted to use the Webhook feature to automatically update the website I was working on when the master branch was updated.

I looked for an easy solution on the internet, but didn’t find anything that worked out of the box. Finally I came up with this code, that worked for me.

The following php file, can be added like http://domain.ch/webhooks/webhook.php?key=someKey to the Webhook section in Gitlab. The key can be anything. It just makes sure that if someone accidentally opens the webpage it won’t trigger an update. It also checks the IP of the client that connects. So the IP of the gitlab server has to be added. The script logs everything into a file: webhook.log. After a check, if the update was to the master branch, it executes a shell script.
<?php//error_reporting(E_ALL);$key = 'someKey';$ip = "xxx.xxx.xxx.xxx";file_put_contents('/var/www/webhook.log','Request on ' . date("F j, Y, g:i a") . ' from ' . $_SERVER['REMOTE_ADDR'] . PHP_EOL, FILE_APPEND);if ($_GET['key'] != $key){echo "no permission 1";file_put_contents('/var/www/webhook.log', 'wrong key' . PHP_EOL, FILE_APPEND);exit(0);}if ($_SERVER['REMOTE_ADDR'] != $ip){echo "no permission 2";file_put_contents('/var/www/webhook.log', 'ip not permitted' . PHP_EOL, FILE_APPEND);exit(0);}$json= file_get_contents('php://input');//file_put_contents('/var/www/webhook.log', PHP_EOL . $json, FILE_APPEND);$jsarr=json_decode($json,true);//file_put_contents('/var/www/webhook.log', PHP_EOL . print_r($jsarr,true), FILE_APPEND);$branch=$jsarr["ref"];file_put_contents('/var/www/webhook.log', 'Branch= ' . $branch . PHP_EOL, FILE_APPEND);// Pushed to master?if ($branch === 'refs/heads/master'){exec("/var/www/webhook.sh");}?>

The shell script is in my case only a few lines. It executes the git pull command and writes it into the logfile.

#!/bin/shcd /var/www/someWebsitegit pull >> /var/www/webhook.log

Make sure that the file is executable, and git is already set up properly in the directory. It has to be set up with the user that executes the script. For me that is www-data.

Gitlab Webhook in PHP
10/06/2013
Posted by m4rCsi