truesocks.net blog
PHP has at least four ways to make an HTTP request, and each of them treats proxies differently. A practical reference with working code, SOCKS5 notes, authentication pitfalls and a debugging routine.
PHP still powers a huge share of the web, and sooner or later many PHP applications need to send outgoing traffic through a proxy: a price monitor that checks regional storefronts, a WordPress plugin that talks to an API from a restricted network, a Laravel job that collects public data, or a corporate server that can only reach the internet through an egress proxy. The trouble is that "set the proxy" means something different for raw cURL, Guzzle, Symfony HttpClient and the old file_get_contents stream wrapper. This guide shows each one with code that works, plus the traps that cost the most time. I tested the examples against HTTP and SOCKS5 endpoints from truesocks.net, but they apply to any proxy with username and password authentication.
All the examples below use one proxy URL format, kept in an environment variable:
# .env
PROXY_URL=http://user:secret@203.0.113.10:8000
# or SOCKS5 with remote DNS
# PROXY_URL=socks5h://user:secret@203.0.113.11:1080
Two details matter. First, URL-encode special characters in the username and password — an @, : or # in a password silently breaks parsing. Use rawurlencode() when you build the URL in code. Second, prefer socks5h over socks5 when the target's location matters: with the h variant the proxy resolves hostnames, so your server's DNS does not leak the lookup or pick a CDN node close to you instead of close to the exit.
The cURL extension gives you the most control, and the other libraries are built on top of it. A minimal, correct setup:
<?php
function proxied_get(string $url, string $proxyUrl): array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => $proxyUrl, // scheme://user:pass@host:port
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_USERAGENT => 'MyApp/1.0 (+https://example.com/bot)',
]);
$body = curl_exec($ch);
$info = curl_getinfo($ch);
$err = curl_errno($ch) ? curl_error($ch) : null;
curl_close($ch);
return ['status' => $info['http_code'], 'body' => $body, 'error' => $err,
'connect_ms' => round($info['connect_time'] * 1000)];
}
$r = proxied_get('https://api.ipify.org?format=json', getenv('PROXY_URL'));
var_dump($r['status'], $r['body'], $r['error']);
If you prefer to keep credentials out of the URL, split them:
curl_setopt($ch, CURLOPT_PROXY, '203.0.113.10:8000');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // or CURLPROXY_SOCKS5_HOSTNAME
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:secret');
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
Note the constant name: CURLPROXY_SOCKS5_HOSTNAME is the equivalent of socks5h. Plain CURLPROXY_SOCKS5 resolves locally.
HTTPS targets through an HTTP proxy use the CONNECT method automatically — you do not need CURLOPT_HTTPPROXYTUNNEL for HTTPS. Set it only if you want to tunnel plain HTTP as well, which some corporate proxies require.
Guzzle accepts a proxy request option, either as a single string or as a per-scheme array with a no list:
<?php
use GuzzleHttp\Client;
$client = new Client([
'timeout' => 30,
'connect_timeout' => 10,
'proxy' => [
'http' => getenv('PROXY_URL'),
'https' => getenv('PROXY_URL'),
'no' => ['localhost', '127.0.0.1', '.internal.example.com'],
],
]);
$res = $client->get('https://api.ipify.org?format=json');
echo $res->getStatusCode(), ' ', $res->getBody(), PHP_EOL;
Things that trip people up:
HTTPS_PROXY from the environment on its own in every setup. It honours HTTP_PROXY only in CLI mode, precisely to avoid the "httpoxy" vulnerability where a client-supplied Proxy: header becomes HTTP_PROXY in CGI. Set the option explicitly rather than relying on env vars.socks5h://user:pass@host:port as the proxy string. With the stream handler (no cURL installed), SOCKS is not supported.$client->get($url, ['proxy' => $otherProxy]). That is the easiest way to rotate exits from a pool.A small rotating pool with retry on proxy-level failures:
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
final class ProxyPool
{
private int $i = 0;
public function __construct(private array $proxies) {}
public function next(): string { return $this->proxies[$this->i++ % count($this->proxies)]; }
}
function fetch_with_pool(Client $c, ProxyPool $pool, string $url, int $tries = 3): ?string
{
for ($n = 0; $n < $tries; $n++) {
$proxy = $pool->next();
try {
$res = $c->get($url, ['proxy' => $proxy, 'http_errors' => false]);
$code = $res->getStatusCode();
if ($code === 407) { throw new RuntimeException('proxy auth failed'); }
if (in_array($code, [403, 429], true)) { usleep(800_000 * ($n + 1)); continue; }
return (string) $res->getBody();
} catch (ConnectException $e) {
// dead or overloaded exit: try the next one
continue;
}
}
return null;
}
The important design choice: a 407 is not retried. It means the credentials or the IP allow-list are wrong, and hammering the proxy with bad credentials can get your account rate limited. Treat 403 and 429 as signals to slow down, not to switch exits faster.
Symfony's client has a proxy option and, unlike Guzzle, reads the standard environment variables by default (http_proxy, https_proxy, no_proxy) when no option is passed:
<?php
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create([
'proxy' => getenv('PROXY_URL'),
'no_proxy'=> 'localhost,127.0.0.1',
'timeout' => 30,
]);
$response = $client->request('GET', 'https://api.ipify.org?format=json');
echo $response->getStatusCode(), ' ', $response->getContent(false), PHP_EOL;
Symfony picks a transport automatically: CurlHttpClient when the cURL extension is available, otherwise NativeHttpClient built on PHP streams. SOCKS proxies require the cURL transport. If you deploy to a container without the cURL extension, a socks5h:// proxy that worked on your laptop will fail in production — check php -m | grep curl in the image.
For per-request proxies, pass the option to request() the same way. For long-running workers (Messenger consumers, queue workers), create the client once and reuse it: connection reuse through the proxy saves a TCP and TLS handshake per request.
Legacy code and many WordPress plugins still use file_get_contents() with a stream context. It only supports HTTP proxies, and the syntax is unusual:
<?php
$auth = base64_encode('user:secret');
$ctx = stream_context_create([
'http' => [
'proxy' => 'tcp://203.0.113.10:8000', // tcp://, not http://
'request_fulluri' => true, // required by many proxies
'header' => "Proxy-Authorization: Basic $auth\r\n",
'timeout' => 30,
],
'ssl' => ['SNI_enabled' => true],
]);
echo file_get_contents('https://api.ipify.org?format=json', false, $ctx);
Three gotchas: the scheme must be tcp://; request_fulluri is needed for plain HTTP through most proxies; and there is no SOCKS support at all. If you control the code, migrate to cURL or one of the clients above.
WordPress has built-in constants for outgoing requests made with the HTTP API (wp_remote_get and friends):
// wp-config.php
define('WP_PROXY_HOST', '203.0.113.10');
define('WP_PROXY_PORT', '8000');
define('WP_PROXY_USERNAME', 'user');
define('WP_PROXY_PASSWORD', 'secret');
define('WP_PROXY_BYPASS_HOSTS', 'localhost, *.wordpress.org');
Bypassing *.wordpress.org keeps updates fast and avoids sending core update traffic through a paid exit.
Laravel's HTTP client wraps Guzzle, so pass the proxy through withOptions(['proxy' => env('PROXY_URL')]). Store the URL in .env and never commit it.
| Method | HTTP proxy | SOCKS5 | Reads env vars | Per-request proxy |
|---|---|---|---|---|
| cURL extension | yes | yes (SOCKS5_HOSTNAME) |
no | yes |
| Guzzle (cURL handler) | yes | yes | CLI only | yes |
| Symfony HttpClient (cURL) | yes | yes | yes | yes |
| file_get_contents | yes | no | no | per context |
When a request through a proxy fails, go through these steps in order:
curl -v -x "$PROXY_URL" https://api.ipify.org — if this fails, PHP is not the problem.CURLOPT_VERBOSE => true with CURLOPT_STDERR pointing to a temp file. Look for the CONNECT line and the proxy's response code.CURLE_COULDNT_RESOLVE_PROXY (5) is DNS for the proxy host, CURLE_COULDNT_CONNECT (7) is a closed port or firewall, CURLE_OPERATION_TIMEDOUT (28) is a slow or dead exit, CURLE_RECV_ERROR (56) during CONNECT often means the proxy rejected the tunnel.HTTP_PROXY variable set by the platform.The language does not decide the proxy type — the target does. Calls to APIs and your own services are fine through datacenter IPv4 or IPv6, which are cheap and fast. Public sites with anti-bot protection usually need ISP or residential addresses, and anything that checks mobile carriers needs mobile proxies. For corporate egress, a single dedicated static IP that partners can put on an allow-list is the cleanest option. If you are building a pool for a PHP job, truesocks.net offers IPv4, IPv6, ISP, residential and mobile proxies in small quantities, which makes it easy to test which type a given target accepts before committing.
Set the proxy explicitly instead of trusting environment variables, use socks5h or CURLPROXY_SOCKS5_HOSTNAME when location matters, never retry a 407, and make sure the cURL extension is present wherever SOCKS is used. With those four habits, PHP and proxies get along fine.
Alex Morozov writes about PHP and Python backends, outbound networking and data collection. Examples were tested with PHP 8.3, Guzzle 7 and Symfony HttpClient 7; option names may differ in older versions. Proxies for the tasks described here — HTTP and SOCKS5, IPv4, IPv6, ISP, residential, mobile and MTProto for Telegram: truesocks.net.
This article was prepared with the help of AI tools and reviewed by the author.