Executing Git Commands via PHP

Executing git commands via PHP

It is definetly possible. I implemented it in one of my projects.
However you should be careful about permissions.

On linux, usually, the exec command will execute using the www-data user.
So you should allow www-data to write and read on your work directory.

One quick and dirty way to do it is : chmod o+rw -R git_directory

Execute GIT command from PHP and get error message back

Try this

/**
* Executes a command and reurns an array with exit code, stdout and stderr content
* @param string $cmd - Command to execute
* @param string|null $workdir - Default working directory
* @return string[] - Array with keys: 'code' - exit code, 'out' - stdout, 'err' - stderr
*/
function execute($cmd, $workdir = null) {

if (is_null($workdir)) {
$workdir = __DIR__;
}

$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w"), // stderr
);

$process = proc_open($cmd, $descriptorspec, $pipes, $workdir, null);

$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

return [
'code' => proc_close($process),
'out' => trim($stdout),
'err' => trim($stderr),
];
}

And then test

$res = execute('git --version')

Array
(
[code] => 0
[out] => git version 2.1.4
[err] =>
)

This will give you what you want

$res = execute('git clone http://...')

Array
(
[code] => 128
[out] =>
[err] => Cloning into '...'...
fatal: unable to access 'http://.../': Could not resolve host: ..
)

Automation of git pull using PHP code

If you use https instead of ssh you can specify user/password directly in the request:

git clone:

exec("git clone https://user:password@bitbucket.org/user/repo.git");

git pull:

exec("git pull https://user:password@bitbucket.org/user/repo.git master");

Alternatives to exposing your password:

  • Use a passwordless ssh key on the target system.
  • Use client-side certificates for https.

Update: if you need to get at the exec command output to debug or verify things, you can pass it an array argument, and then output using standard iterative techniques to the location of your choice. Here is an example that simply prints the output:

function execPrint($command) {
$result = array();
exec($command, $result);
print("<pre>");
foreach ($result as $line) {
print($line . "\n");
}
print("</pre>");
}
// Print the exec output inside of a pre element
execPrint("git pull https://user:password@bitbucket.org/user/repo.git master");
execPrint("git status");

Since the $result array will be appended to, and not overwritten, by exec() you can also use a single array to keep a running log of the results of exec commands.



Related Topics



Leave a reply



Submit