How to Use an HTTP Proxy in PHP with cURL

PHP’s cURL extension can send a request through a specified proxy and report how far it got. Compare the direct and proxied results to check the route and identify the first failure.

Laptop and rack servers joined by purple Ethernet cables through a compact gateway

Check which PHP runtime will make the request

Start in the environment where the request will run. From a terminal, run php --ri curl to check that PHP loads the cURL extension and to see the libcurl and TLS versions underneath it. php --ini shows the configuration files used by that terminal command. A framework worker, PHP-FPM pool or scheduled job can use a different PHP installation, configuration file, CA bundle and environment. If the command works in your shell and fails in the app, compare those details from the affected process. PHP cURL requirements.

Use a maintained PHP 8 release with ext-curl enabled. The script below uses a proxy address in PROXY_URL and accepts optional Basic credentials from PROXY_USER and PROXY_PASSWORD. Set the address to the host and port assigned to your account, such as http://proxy.example:3128. Keep secrets in your process environment through your deployment’s secret mechanism. Supply both credential variables for an authenticated proxy. Leave both unset for a proxy that authorizes your source IP.

Send an HTTPS request through an explicit HTTP proxy

Save the example as proxy-check.php, set the environment values in the process running it and run php proxy-check.php. The proxy address uses http:// because this example makes an ordinary HTTP connection to the proxy. The destination uses https://. cURL sends CONNECT to request a tunnel and negotiates TLS with TestMyProxies through that tunnel. Make sure your endpoint supports the protocol and authentication method in the example. Compare HTTP, HTTPS and SOCKS5 proxies.

<?php
declare(strict_types=1);

if (!extension_loaded('curl')) {
    fwrite(STDERR, "Enable the PHP cURL extension.\n");
    exit(2);
}

$proxy = getenv('PROXY_URL');
$parts = $proxy === false ? [] : parse_url($proxy);
if (($parts['scheme'] ?? '') !== 'http' ||
    empty($parts['host']) || ($parts['port'] ?? 0) < 1 ||
    array_intersect(['user', 'pass', 'path', 'query', 'fragment'], array_keys($parts))) {
    fwrite(STDERR, "Set PROXY_URL to http://host:port. Supply credentials separately.\n");
    exit(2);
}

$options = [
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
    CURLOPT_NOPROXY => '',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
];

$user = getenv('PROXY_USER');
$password = getenv('PROXY_PASSWORD');
if ($user !== false || $password !== false) {
    if ($user === false || $user === '' || $password === false) {
        fwrite(STDERR, "Set both proxy credential variables.\n");
        exit(2);
    }

    $options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC;
    $options[CURLOPT_PROXYUSERNAME] = $user;
    $options[CURLOPT_PROXYPASSWORD] = $password;
}

$curl = curl_init('https://testmyproxies.com/api/my-ip');
if ($curl === false || !curl_setopt_array($curl, $options)) {
    fwrite(STDERR, "Could not configure the cURL request.\n");
    exit(2);
}

$body = curl_exec($curl);
$error = curl_errno($curl);
$connectCode = curl_getinfo($curl, CURLINFO_HTTP_CONNECTCODE);
$httpCode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
fprintf(STDERR, "cURL=%d CONNECT=%d HTTP=%d\n", $error, $connectCode, $httpCode);

if ($body === false) {
    fwrite(STDERR, curl_strerror($error) . PHP_EOL);
    exit(1);
}

if ($httpCode !== 200) {
    fwrite(STDERR, "The IP endpoint returned an unexpected HTTP status.\n");
    exit(1);
}

$result = json_decode($body, true);
$ip = $result['ip'] ?? null;
if (!is_string($ip) || filter_var($ip, FILTER_VALIDATE_IP) === false) {
    fwrite(STDERR, "The response did not contain a valid IP address.\n");
    exit(1);
}

echo $ip, PHP_EOL;

The explicit CURLOPT_PROXY setting selects the proxy for this request. Setting CURLOPT_NOPROXY to an empty string overrides the inherited destination exclusion list for this approved test. Remove that override from application code if it should honor the deployment’s exclusions. The eight-second connection limit covers the connection phase, including name resolution and protocol handshakes. The 20-second limit covers the whole transfer, including connection time. cURL bypass rules · cURL connection time limit.

Interpret the cURL error, CONNECT status and HTTP status

The script prints its three diagnostic numbers to standard error and a successful exit IP to standard output. On a working tunnel, expect cURL=0 CONNECT=200 HTTP=200. Compare the printed address with the exit IP your provider reports for this endpoint. The address you dialed belongs to the proxy gateway, which can accept connections for multiple exit addresses. A rotating endpoint can select different addresses on repeated requests, so compare against the expected session or pool. Read the proxy test result.

  • A nonzero cURL error describes a failure reported by the transfer library. For example, code 5 points to proxy DNS resolution and code 28 means a timeout. Compare the other two values to see how far the transfer got. A timeout can occur before the tunnel opens or after the destination starts responding.
  • The CONNECT status records the HTTP response that opened or rejected the tunnel. A 407 here calls for checking proxy credentials, the configured authentication method or the source IP allowlist. Zero indicates that cURL has no CONNECT status to report.
  • The HTTP status records the response to the request inside the tunnel. A 403 here calls for checking access rules for the destination or a gateway in front of it. Zero indicates that no destination response code was recorded. For example, a rejected CONNECT may produce a 407 in the tunnel field and zero in this one.

CURLOPT_FAILONERROR is left at its default so the script can examine a destination error response without treating its HTTP status alone as a cURL transport error. A failed transfer can still carry a usable status from an earlier step, so the script collects all three values before deciding whether to show the IP. libcurl error codes · CONNECT status reference · HTTP response code reference.

Find the cause of proxy authentication or certificate errors

If the proxy refuses authentication, confirm the username, password and method with its operator. The example uses Basic authentication, which sends the encoded credentials across the client-to-proxy connection. On an ordinary HTTP proxy this leg is unencrypted, even with an HTTPS destination. For a provider-supported HTTPS proxy endpoint, use the appropriate transport and CA trust settings for both TLS connections. Keep certificate verification enabled. HTTP 407 troubleshooting · Diagnose proxy TLS certificate errors.

If PHP reports a certificate error after a successful CONNECT, check the destination hostname and the CA bundle available to that PHP process. A CLI build and a web server worker may use different configuration files, accounts or trust stores. Ask the network operator for the approved CA configuration if HTTPS inspection is expected. Retry the same URL with the same proxy from the affected environment after correcting the trust setup. cURL certificate verification.

For a restricted deployment, keep the proxy address and target URL in operator-managed configuration. When investigating a routing difference, check for a framework or HTTP client wrapper that supplies its own proxy settings or options. Run the fixed-URL example separately, then test the framework client with the same settings. Matching the environment and destination makes the result useful for identifying application configuration differences.

When sending an error report, record the PHP and libcurl versions, the three diagnostic numbers and which process made the request. Omit proxy passwords, authentication headers and tokenized URLs. Compare the results with a command-line cURL check from the same host if you need to isolate differences between PHP and the underlying connection. Test a proxy with cURL.

All proxy testing guides · Open the proxy tester