Git Deployment PHP
Nginx + PHP
https://docs.github.com/en/developers/webhooks-and-events/webhooks/creating-webhooks
git clone https://{{TOKEN}}:x-oauth-basic@github.com/ORG_ADI/REPO_ADI.git /var/www/repo
chown -R www-data:www-data /var/www/repo/
<?php
$ghHookIps = ['185.199.108', '143.55.64.', '140.82.112.', '192.30.252.'];
if ($_SERVER["HTTP_X_FORWARDED_FOR"]) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} elseif($_SERVER["HTTP_CF_CONNECTING_IP"]){
$ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
}else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$allowed = false;
foreach ($ghHookIps as $allow) {
if (stripos($ip, $allow) !== false) {
$allowed = true;
break;
}
}
$allowed = true;
if (!$allowed) {
header('HTTP/1.1 403 Forbidden');
echo 'Restricted area';
exit;
}
if(!isset($_SERVER['HTTP_X_GITHUB_EVENT']) || $_SERVER['HTTP_X_GITHUB_EVENT'] !== 'push'){
header('HTTP/1.1 400 Bad Request');
echo 'Bad Request';
exit;
}
flush();
$repoDir = '/var/www/test';
$branch = 'master';
$logDir = '/var/log/deploy';
$gitComm = "$(which git) --git-dir=$repoDir/.git --work-tree=$repoDir ";
$commands = [
"cd $repoDir",
$gitComm . " reset HEAD --hard",
$gitComm . " fetch origin;",
$gitComm . " checkout $branch;",
$gitComm . " pull;"
];
print "####### Started - " . date('Y-m-d H:i:s') . " #######\n";
foreach ($commands as $command) {
exec($command . ' 2>&1;', $output, $exitCode);
if ($exitCode !== 0) {
print 'Command Exec Error. Comm : ' . $command . PHP_EOL;
file_put_contents($logDir . '/error.log',print_r($output,true),FILE_APPEND);
break;
}
print 'Command Exec Success. Comm : ' . $command . PHP_EOL;
file_put_contents($logDir . '/success.log',print_r($output,true),FILE_APPEND);
}
print "####### Ended - " . date('Y-m-d H:i:s') . " #######\n";