Skip to content

Instantly share code, notes, and snippets.

@ndunks ndunks/gitlab.php
Created Oct 16, 2018

Embed
What would you like to do?
Gitlab Hook auto deploy live web server
<?php
// CONFIG
// This token must sent with the request, for security
$TOKEN='XXXXXXXXXXX';
$LOCAL_GIT=realpath(dirname(__DIR__) . '/app.git');
$PRODUCTION_DIR=realpath(dirname(__DIR__) . '/public_html');
$REMOTE = 'origin';
$LOCAL_BRANCH = 'master';
$LOG_FILE = __DIR__ . '/log.txt';
date_default_timezone_set("Asia/Jakarta");
set_time_limit(0);
$log_handle = fopen($LOG_FILE, 'a');
if( !$log_handle )
{
die('FATAL ERROR CANNOT OPEN LOG FILE');
}
function write_log($msg){
global $log_handle;
return fwrite($log_handle, rtrim( $msg ) . "\n" );
}
// Log separator
fwrite($log_handle, str_repeat('-', 10) . ' START ' .
date('Y-m-d H:i:s') . ' ' . str_repeat('-', 10) . "\n" );
$request_token = @$_SERVER['HTTP_X_GITLAB_TOKEN'];
write_log('User: ' . shell_exec('whoami'));
write_log('Client: ' . @$_SERVER["HTTP_USER_AGENT"]);
if(!function_exists('shell_exec'))
{
write_log("ERROR: no shell_exec function.");
header("HTTP/1.0 500 Internal Error");
exit;
}
$GIT = shell_exec('which git');
if(empty($GIT)) {
write_log("ERROR: No git binary found.");
header("HTTP/1.0 500 Internal Error");
exit;
}
if( ! $LOCAL_GIT ){
write_log("ERROR: Invalid local repo dir.");
header("HTTP/1.0 500 Internal Error");
exit;
}
if( ! $PRODUCTION_DIR ){
write_log("ERROR: Invalid prod dir.");
header("HTTP/1.0 500 Internal Error");
exit;
}
if( $request_token !== $TOKEN ){
write_log("ERROR: Invalid token " . $request_token);
header("HTTP/1.0 403 Forbidden");
exit;
}
// Change work dir to local GIT repo
chdir($LOCAL_GIT);
write_log('Fetching remote..');
$result = shell_exec('git fetch ' . $REMOTE . ' 2>&1');
write_log($result);
write_log('Cleaning local changes..');
$result = shell_exec('git stash drop');
write_log($result);
write_log('Updating files into production..');
$result = shell_exec('GIT_WORK_TREE="' . $PRODUCTION_DIR . '" git pull -f 2>&1');
write_log($result);
$result = shell_exec($cmd);
write_log($result);
fwrite($log_handle, str_repeat('-', 10) . ' DONE ' .
date('Y-m-d H:i:s') . ' ' . str_repeat('-', 10) . "\n" );
fclose($log_handle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.