All posts

Fix Load Balancer Error in PHP

Resolve PHP application errors behind load balancers including $_SERVER variables, session handling, and file upload proxying.

PHP Behind a Load Balancer

PHP relies heavily on $_SERVER variables for request information. Behind a load balancer, these variables reflect the proxy connection, not the client — leading to broken HTTPS detection, wrong client IPs, and session issues.

HTTPS Detection

PHP checks $_SERVER['HTTPS'], but the load balancer terminates SSL:

// In your bootstrap or .htaccess
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $_SERVER['HTTPS'] = 'on';
}

Or in Apache .htaccess:

SetEnvIf X-Forwarded-Proto "https" HTTPS=on

Real Client IP

function getClientIp(): string {
    $headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            // X-Forwarded-For can contain multiple IPs
            $ips = explode(',', $_SERVER[$header]);
            return trim($ips[0]);
        }
    }
    return $_SERVER['REMOTE_ADDR'];
}

Session Handling

File sessions break with multiple servers. Switch to Redis:

; php.ini
session.save_handler = redis
session.save_path = "tcp://redis-service:6379"

Health Check

// healthz.php
http_response_code(200);
echo 'ok';
exit;

Keep it simple — don't include your framework bootstrap, which might fail and return a 500 to the load balancer.

Bugsly's PHP SDK hooks into error handlers and exception handlers to capture errors with request context, including the real client IP parsed from proxy headers.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free