Deploying PHP with Git
Manual FTP uploads are error‑prone and make rollbacks impossible. Using Git to push code directly to your production server gives you atomic, versioned deployments that mirror your development tree.
Central bare repository
On your server, initialise a bare repository to act as the deployment target. A bare repository has no working tree; it simply stores Git objects and references:
mkdir -p /var/www/deploy.git
cd /var/www/deploy.git
git init --bare
Add this remote to your local project with git remote add prod user@server:/var/www/deploy.git. The server will now receive your commits when you push to prod.
Hook into checkout
A post‑receive hook checks out the new code into a working directory. This script runs automatically after each push:
#!/bin/sh
GIT_WORK_TREE=/var/www/production
export GIT_WORK_TREE
umask 022
git --work-tree=$GIT_WORK_TREE --git-dir=/var/www/deploy.git checkout -f
Place the script in deploy.git/hooks/post-receive and make it executable. The umask ensures correct permissions. On push, the hook overwrites the contents of /var/www/production with your repository state.
Environment configuration
Never commit secrets to version control. Use a .env file or include local config outside the repository. At deploy time, symlink configuration files into your working tree.
Zero‑downtime updates
To avoid requests hitting partially updated code, deploy to a new directory then atomically update a symlink pointing your webroot to the latest release. Old releases remain on disk for rollback. A simple deployment script could look like this:
#!/bin/sh
set -e
DEPLOY_DIR=/var/www/releases/$(date +%Y%m%d%H%M%S)
git --work-tree=$DEPLOY_DIR --git-dir=/var/www/deploy.git checkout -f
ln -sfn $DEPLOY_DIR /var/www/production
With Git deployments, you gain repeatability and a full history of changes. Combine with automated tests and continuous integration for a robust pipeline.