← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 4 of 10

PHP Git Integration

Introduction to Git

Git is a version control system that tracks every change to your codebase over time; PHP scripts can shell out to Git commands to automate checks like verifying the working tree is clean before deploying.

Example: Introduction to Git

php
<?php
$status = shell_exec('git status --porcelain 2>&1');
echo $status === '' ? "Working tree is clean" : "There are uncommitted changes";
?>

Initializing Repositories

You can create a .gitignore file or run 'git init' programmatically from PHP, which is occasionally useful for tooling that scaffolds new projects automatically.

Example: Initializing Repositories

php
<?php
// shell_exec('git init');
file_put_contents('.gitignore', "vendor/\n.env\n");
echo file_get_contents('.gitignore');
?>

Running Git Commands

shell_exec() lets a PHP script run arbitrary shell commands, including Git commands -- but on shared hosting you should suppress and check errors carefully, since shell access is often restricted or risky.

Example: Running Git Commands

php
<?php
$output = shell_exec('git --version 2>&1');
echo $output !== null ? trim($output) : "shell_exec unavailable or restricted";
?>

Automating Commits

A backup script can stage modified files and commit them automatically on a schedule, giving you an audit trail of changes even for data that isn't normally version-controlled by hand.

Example: Automating Commits

php
<?php
// shell_exec('git add . && git commit -m "Automated backup"');
echo "A scheduled script could stage and commit changes automatically";
?>

Safe Environment Checks

Running Git commands from a live, internet-facing script is dangerous unless carefully locked down -- an exposed .git folder or an unguarded shell_exec() endpoint can leak your entire source history to an attacker.

Example: Safe Environment Checks

php
<?php
$path = ".git/config";
if (file_exists($path)) {
    echo "Warning: .git folder should never be publicly reachable";
} else {
    echo "No exposed .git folder found here";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.