What Are Webhooks?
Webhooks are HTTP callbacks triggered by events. GitHub, GitLab, and Bitbucket can send a POST request to your server whenever code is pushed, allowing automatic deployments.
Simple PHP Webhook Handler
<?php
$secret = "your-webhook-secret";
$signature = $_SERVER["HTTP_X_HUB_SIGNATURE_256"] ?? "";
$payload = file_get_contents("php://input");
// Verify signature
$expected = "sha256=" . hash_hmac("sha256", $payload, $secret);
if (!hash_equals($expected, $signature)) {
http_response_code(403);
die("Invalid signature");
}
$data = json_decode($payload, true);
// Only deploy on push to main
if ($data["ref"] === "refs/heads/main") {
$output = shell_exec("cd /var/www/myapp && git pull origin main 2>&1");
$output .= shell_exec("cd /var/www/myapp && composer install --no-dev 2>&1");
file_put_contents("/var/log/deploy.log", date("Y-m-d H:i:s") . "\n" . $output . "\n\n", FILE_APPEND);
echo "Deployed successfully";
} else {
echo "Not main branch, skipping";
}
Nginx Configuration
location /webhook {
# Restrict to GitHub IP ranges (optional)
allow 140.82.112.0/20;
allow 185.199.108.0/22;
deny all;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/webhook.php;
}GitHub Setup
- Go to your repo → Settings → Webhooks
- Payload URL:
https://example.com/webhook - Content type:
application/json - Secret: your shared secret
- Events: Just the push event
Security
- Always verify webhook signatures
- Use HTTPS for the endpoint
- Restrict access by IP when possible
- Log all deployments for audit trail
- Run deploys as a non-root user