Control Git with PHP

gitphp
Git is getting popular day by day and there are many web front-ends for git available on the internet. In this article, i will give you an alternative option to work with git directly from PHP, i think it can be handy in some cases.

To start working with it, we will need to find out apache web user on the system. Normally, it’s www-data on linux and _www on Mac then we need to switch to that user using this command

su www-data; # or _www</pre>

then we create .ssh directory in www-data user home to generate & store ssh keys

# make new .ssh home for www user
mdkir /var/www/.ssh;
# change permission of .ssh directory
chmod -Rf 777 /var/www/.ssh;
# generate new key
ssh-keygen -t rsa;

you will also need to allow www-data user read/write permission, i have an article for it here, but for short, you can use these command

# change group ownershipng to www-data user, user _www for MacOSX
sudo chown -R :www-data [path_to_your_source_code_directory]
sudo chmod -R g+w [path_to_your_source_code_directory]

As a git user, you know that git requires your ssh public key to be added to git so you can pull/push code. in this case, we need to add www-data user ssh key to git repository. please do it like you always do. After having www-data user ssh key added, you can execute following command to do initial git pull to accept git server.

# add /var/www/.ssh/id_rsa.pub to your git deploy key then execute these line
cd GIT_REPO_FOLDER;
git pull origin; # it will ask you to accept, choose yes.
exit; # return to your user

finally, create php script like this (note : this is just an example for magento devsite update)
deploygit.php

<?php
echo "\n1.switch branch\n";
echo(exec('git checkout devsite;'));

echo "\n\n2.update branch\n";
echo(shell_exec('git pull origin devsite 2>&1'));

echo "\n\n3.clean cache\n";
echo(exec('rm -rfv var/cache/*;'));

echo("\n=======");
die("\ndone!");
?>

place it at root of your website source code, execute [you_web_site_base_url]/deploygit.php to run script

Leave a Comment