从PHP脚本中运行git命令

I have a file upload form and after the file uploads I want to push the files up to GitHub by running:

git add .
git commit -m "some message"
git push origin master

How do I go about this? I've seen examples of using exec() but that makes me nervous.

shell_exec('cd /var/www/vhost/xxx.com/httpdocs/clients/portal/upoads/54 && /usr/bin/git add -A');
shell_exec('cd /var/www/vhost/xxx.com/httpdocs/clients/portal/upoads/54 && /usr/bin/git commit -m "something 1"');
shell_exec('cd /var/www/vhost/xxx.com/httpdocs/clients/portal/upoads/54 && /usr/bin/git push origin master');

Those commands don't error but don't work either. Do I need to grant access to the apache user to use the ssh key?

i guess is permission problems, you can use exec() , and get the error info by $output

exec($your_command.' 2>&1', $output, $return_var);
var_dump($output);

Do I need to grant access to the apache user to use the ssh key?

Yes.

This means you have to copy the key somewhere that the apache user can read it. SSH won't work unless the key file is readable by the user only (i.e. 0600 permissions on the key file).

Copy the key like:

mkdir -p --mode=0700 ~apache/.ssh    
cp /my/id_rsa ~apache/.ssh/id_rsa
chown -R apache:apache ~apache/.ssh/id_rsa
chmod 0600 ~apache/.ssh/id_rsa

Also, you don't need to cd every time you want to run the command. Use GIT_DIR:

putenv('GIT_DIR=/path/to/git/repo')
shell_exec('git commit ...')

I solved it. I ran all of this as root user.

Inside my PHP script I ran

exec("whoami"); 

to get the user that is running that script. Then I ran

cat /etc/passwd

to get the home directory for that user (/var/www/vhost/mydomain.com)

I noticed that on my web server (Centos 7) that all my web files were chown'd as opcode:psacln so I created a .ssh directory inside opcode's home folder:

mkdir -p --mode=0700 /var/www/vhost/mydomain.com/.ssh  
cd (back to root)  
cp .ssh/id_rsa /var/www/vhost/mydomain.com/.ssh/id_rsa
chown -R opcode:psacln /var/www/vhost/mydomain.com/.ssh/id_rsa
chmod 0600 /var/www/vhost/mydomain.com/.ssh/id_rsa

The thing I was missing was that I had to also move my known_hosts file over, since the script I was using wasn't adding to it.

cp .ssh/known_hosts /var/www/vhost/mydomain.com/.ssh/known_hosts
chmod 0600 /var/www/vhost/mydomain.com/.ssh/known_hosts

Of course, I had to login to my server at the command line and do an initial commit to the repo in order to get it added to my known_hosts file, before I copied it over. Hope this helps someone.