PHP cURL Proxy: Authenticated Requests and SOCKS5
Send PHP cURL and Guzzle requests through an authenticated proxy, switch to SOCKS5, verify the exit IP and handle 407s and timeouts.
To send a PHP cURL request through an authenticated proxy, set CURLOPT_PROXY to the proxy's http://HOST:PORT, put the credential in CURLOPT_PROXYUSERNAME and CURLOPT_PROXYPASSWORD, and leave TLS verification on; libcurl opens a CONNECT tunnel for an https:// target by itself. For SOCKS5, change the scheme to socks5h:// (or set CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME) and change nothing else. In Guzzle the same configuration is the proxy request option, a URL with the credential percent-encoded inside it. Every example on this page was run on December 1, 2026 with PHP 8.3 (libcurl 8.11.1), Guzzle 7.17 and Guzzle 8.6 against Node4's rotating datacenter gateway, and the refusal output shown is what those runs printed.
TL;DR
CURLOPT_PROXYUSERNAMEandCURLOPT_PROXYPASSWORDtake the credential verbatim.CURLOPT_PROXYUSERPWDand auser:pass@inside the proxy URL are URL-decoded, so a password containing%,:or@must be percent-encoded there.- A wrong credential on an HTTPS target is not a 407 response in PHP:
curl_execreturnsfalse,curl_errnois 56 (7 on newer libcurl builds) and the 407 is inCURLINFO_HTTP_CONNECTCODEeither way. - A SOCKS5 refusal is
curl_errno97. On PHP 8.2 and laterCURLINFO_PROXY_ERRORnames the reply as aCURLPX_*constant; the raw reply byte is in the error string on every version. - The exit is chosen per connection (per request for a plain
http://target through the HTTP port). A reused handle keeps its tunnel and its exit; a session id in the username holds one exit across handles.
Before you start
- PHP 8.0 or later with the curl extension (
php -m | grep curl). The code usesmatch,str_containsandstr_starts_with.CURLINFO_PROXY_ERROR, theCURLPX_*constants andCURLE_PROXYexist only on PHP 8.2 and later built against libcurl 7.73 or newer, so the code below compares the numeric values (97 for the error, 19 to 23 and 33 for the SOCKS5 detail) and, when the constant is missing, reads the reply number from the error string instead. - A proxy credential. On Node4 it is the one username and password under Auth & IP Access in Account Settings; it works on every product the account holds an active plan for, and a paid account can create up to 5 credential sets so each worker fleet gets its own. The username is letters, digits and underscores, never a hyphen, because on the gateway products a hyphen starts a targeting segment.
- An HTTPS target you are allowed to request. Node4's echo endpoint at
https://node4.io/api/tools/ipreturns the connecting address and its country as JSON, which is the exit check used below. The residential gateway does not open node4.io itself, so when you point this code at residential, swap in a third-party echo such ashttps://ipinfo.io/json, which returns the sameipandcountryfields. - A plan that reaches the endpoint you are testing. The free tier is static shared datacenter over HTTP(S) only (3 proxies, 1 GB a month): it exercises the HTTP code path with a host and port from the Proxies page, but the rotating and residential gateways answer a free credential with a 407, and SOCKS5 is refused for free accounts.
The examples use the Rotating Datacenter gateway. The hosts and ports for every gateway product:
| Product | Host | HTTP port | SOCKS5 port | Billed by |
|---|---|---|---|---|
| Rotating Datacenter | gw-rotating_datacenter.node4.io | 8083 | 1083 | gigabyte |
| Rotating Unmetered | gw-rotating_unmetered.node4.io | 8084 | 1084 | concurrent connections |
| Residential | gw-residential.node4.io | 8082 | 1082 | gigabyte |
| Shared and dedicated datacenter | the address beside each proxy on Proxies | on the Connect card | on the Connect card | per proxy, monthly |
The two rotating products draw the same exit pool, in the US, Italy and Spain, and differ only in the meter: pay by the gigabyte if you move a little data, by concurrency if you move a lot. Rotating Datacenter pricing and Rotating Unmetered pricing show the two meters. The code below does not change between them; only the host and port do.
The working request through an authenticated HTTP proxy
Save this as proxy_fetch.php. It builds the gateway username, sets the proxy options, and turns whatever libcurl reports into one cause string you can log and branch on, without ever printing the password.
<?php
declare(strict_types=1);
/**
* Build the gateway username. Targeting rides in the username, so this is
* where a country or a sticky session is chosen. Order: base, country, session.
*/
function gateway_username(string $base, ?string $country = null, ?string $session = null): string
{
if (!preg_match('/^[A-Za-z0-9_]+$/', $base)) {
throw new InvalidArgumentException('base username: letters, digits and underscores only, no hyphens');
}
if ($country !== null && !preg_match('/^[a-z]{2}$/', $country)) {
throw new InvalidArgumentException('country: a two-letter lowercase code such as us, it or es');
}
if ($session !== null && !preg_match('/^[A-Za-z0-9]{1,32}$/', $session)) {
throw new InvalidArgumentException('session: 1 to 32 letters and digits');
}
return $base
. ($country !== null ? '-country-' . $country : '')
. ($session !== null ? '-session-' . $session : '');
}
/**
* cURL options for one request through an authenticated proxy.
* $proxyUrl is "http://HOST:PORT" or "socks5h://HOST:PORT". Pass null to go direct.
* $blocks collects one entry per response block (the CONNECT answer, any interim
* response, the final response), so a header keeps the block it arrived in.
*/
function proxy_options(?string $proxyUrl, string $username, string $password, array &$blocks): array
{
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_NOPROXY => '', // a NO_PROXY variable in the environment cannot bypass the proxy
CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$blocks): int {
$trimmed = trim($line);
if (str_starts_with($trimmed, 'HTTP/')) {
$blocks[] = ['status_line' => $trimmed, 'headers' => []]; // a new block starts at each status line
} elseif ($blocks !== [] && str_contains($trimmed, ':')) {
[$name, $value] = explode(':', $trimmed, 2);
$blocks[array_key_last($blocks)]['headers'][strtolower(trim($name))] = trim($value);
}
return strlen($line);
},
];
if ($proxyUrl === null) {
$options[CURLOPT_PROXY] = ''; // an empty string disables any proxy from the environment too
return $options;
}
$options[CURLOPT_PROXY] = $proxyUrl;
$options[CURLOPT_PROXYUSERNAME] = $username; // taken verbatim, unlike CURLOPT_PROXYUSERPWD, which URL-decodes
$options[CURLOPT_PROXYPASSWORD] = $password; // so a password with ":" or "%" needs no encoding here
$options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC;
return $options;
}
/**
* The gateway's own headers. On a new connection with a CONNECT tunnel the first block is the
* gateway's answer to CONNECT, kept apart from the target's; on plain HTTP the gateway adds its
* headers to the one response block, beside the target's.
*/
function gateway_headers(array $blocks, int $connect): array
{
if ($blocks === []) {
return [];
}
return $connect !== 0 ? $blocks[0]['headers'] : $blocks[array_key_last($blocks)]['headers'];
}
/** errno 97: name the SOCKS5 stage that failed. PHP 8.2+ reads CURLINFO_PROXY_ERROR; older builds parse the reply byte. */
function socks5_cause(int $proxyErr, string $error): string
{
if ($proxyErr === 0 && preg_match('/\((\d)\)/', $error, $m)) {
$proxyErr = [1 => 20, 2 => 23, 3 => 22, 4 => 21, 5 => 19][(int) $m[1]] ?? 0; // reply byte to CURLPX_* value
}
return match ($proxyErr) {
33 => 'socks5-auth-rejected', // CURLPX_USER_REJECTED: the username and password exchange failed
23 => 'socks5-not-allowed', // reply 2, CURLPX_REPLY_NOT_ALLOWED: on Node4 any 407 cause OR the connection ceiling
20 => 'socks5-unavailable', // reply 1, CURLPX_REPLY_GENERAL_SERVER_FAILURE: the session cannot be pinned now
21 => 'socks5-host-unreachable', // reply 4, CURLPX_REPLY_HOST_UNREACHABLE: country with no exits, or target unreachable
22 => 'socks5-network-unreachable', // reply 3, CURLPX_REPLY_NETWORK_UNREACHABLE
19 => 'socks5-connection-refused', // reply 5, CURLPX_REPLY_CONNECTION_REFUSED: the target refused the exit
0 => 'socks5-unknown', // no detail: keep curl_error() in the log
default => 'socks5-error-' . $proxyErr,
};
}
/**
* Turn the handle's state after curl_exec into one cause string you can log and branch on.
* The gateway's answer (CURLINFO_HTTP_CONNECTCODE, or its markers on plain HTTP) is judged
* separately from the target's status: a 502 from the target is the target's 502.
*/
function classify_result(CurlHandle $ch, int $errno, string $body, array $blocks): array
{
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); // the final response, 0 if there was none
$connect = curl_getinfo($ch, CURLINFO_HTTP_CONNECTCODE); // the gateway's answer to CONNECT, 0 if none
$proxyErr = defined('CURLINFO_PROXY_ERROR') ? curl_getinfo($ch, CURLINFO_PROXY_ERROR) : 0; // SOCKS5 detail, PHP 8.2+
$gw = gateway_headers($blocks, $connect);
$plain = $connect === 0 && $status !== 0; // a plain-HTTP response: the gateway's or the target's
$cause = match (true) {
// The gateway refused the CONNECT, so no tunnel and no target response exist.
$connect === 407 => 'proxy-auth', // wrong credential, whitelist miss, no plan for this gateway
$connect !== 0 && $connect !== 200 => 'proxy-refused-' . $connect, // 502 country, 503 session, 429 ceiling
// Plain HTTP: a gateway refusal carries the gateway's markers; without them the status is the target's.
$plain && $status === 407 => 'proxy-auth',
$plain && $status === 429 && isset($gw['x-node4-conn-limit']) => 'proxy-refused-429',
$plain && $status === 503 && ($gw['x-node4-sticky'] ?? '') === 'unavailable' => 'proxy-refused-503',
$plain && $status === 502 && str_starts_with($body, 'no exit available') => 'proxy-refused-502',
// Transport failures.
$errno === 97 => socks5_cause($proxyErr, curl_error($ch)), // 97 = CURLE_PROXY
$errno === CURLE_OPERATION_TIMEDOUT => 'timeout',
$errno === CURLE_COULDNT_RESOLVE_PROXY,
$errno === CURLE_COULDNT_CONNECT => 'proxy-unreachable', // host, port or firewall
$errno !== 0 => 'curl-' . $errno,
// A response from the target, through an open tunnel or as plain HTTP.
$status >= 200 && $status < 300 => 'ok',
default => 'target-http-' . $status,
};
return ['cause' => $cause, 'status' => $status, 'connect' => $connect, 'errno' => $errno,
'error' => curl_error($ch), 'proxy_error' => $proxyErr, 'body' => $body,
'gateway_headers' => $gw, 'blocks' => $blocks];
}
function proxy_fetch(string $url, ?string $proxyUrl, string $username, string $password): array
{
$blocks = [];
$ch = curl_init($url);
curl_setopt_array($ch, proxy_options($proxyUrl, $username, $password, $blocks));
$body = curl_exec($ch);
$result = classify_result($ch, curl_errno($ch), is_string($body) ? $body : '', $blocks);
curl_close($ch);
return $result;
}Then run.php, which fetches the echo endpoint twice, once direct and once through the proxy, so the two addresses can be compared:
<?php
declare(strict_types=1);
require __DIR__ . '/proxy_fetch.php';
$proxyUrl = getenv('NODE4_PROXY_URL') ?: null; // http://gw-rotating_datacenter.node4.io:8083
$user = getenv('NODE4_PROXY_USER') ?: '';
$pass = getenv('NODE4_PROXY_PASS') ?: '';
$echo = 'https://node4.io/api/tools/ip';
$direct = proxy_fetch($echo, null, '', '');
$viaProxy = proxy_fetch($echo, $proxyUrl, $user, $pass);
printf("direct: %s %s\n", $direct['cause'], json_decode($direct['body'], true)['ip'] ?? '-');
printf("proxied: %s", $viaProxy['cause']);
if ($viaProxy['cause'] === 'ok') {
$seen = json_decode($viaProxy['body'], true);
printf(" exit=%s country=%s sticky=%s\n", $seen['ip'], $seen['country'],
$viaProxy['gateway_headers']['x-node4-sticky'] ?? 'n/a'); // from the gateway's block, never the target's
} else {
printf(" errno=%d connect=%d status=%d error=%s\n",
$viaProxy['errno'], $viaProxy['connect'], $viaProxy['status'], $viaProxy['error']);
}Export NODE4_PROXY_URL, NODE4_PROXY_USER and NODE4_PROXY_PASS in the shell (or your secret store) and run php run.php.
Expected result: the direct line prints your own public address and the proxied line prints ok with a different address and a country of US, IT or ES. With a credential the gateway does not accept, the second line is exactly this:
proxied: proxy-auth errno=56 connect=407 status=0 error=CONNECT tunnel failed, response 407The target was HTTPS, so libcurl asked the proxy for a CONNECT tunnel, the proxy answered 407, and libcurl reported a transport failure (CURLE_RECV_ERROR, 56; newer libcurl builds report CURLE_COULDNT_CONNECT, 7, for the same refusal) with no response object at all. CURLINFO_RESPONSE_CODE is 0. The 407 lives only in CURLINFO_HTTP_CONNECTCODE and in the error string, and code that checks curl_getinfo($ch, CURLINFO_HTTP_CODE) for 407 never sees it. Older libcurl builds word the same failure Received HTTP code 407 from proxy after CONNECT. On a plain http:// target the proxy's 407 is an ordinary response instead, with the body proxy authentication required, which is why classify_result checks both places. It reads the connect code before the target status for a reason: once CONNECT returned 200, any status that follows, a 502 included, came from the target through the tunnel, and classify_result reports it as target-http-502. A plain-HTTP 502 counts as the gateway's only when it carries the gateway's body (no exit available); otherwise it is the target's.
What each option does
| Option | What it does | Why it is set this way |
|---|---|---|
CURLOPT_PROXY | Proxy host, port and scheme. http:// is the default when no scheme is given; socks5h:// selects SOCKS5 with proxy-side DNS | A hostname needs the port spelled out; libcurl assumes 1080 otherwise |
CURLOPT_PROXYUSERNAME, CURLOPT_PROXYPASSWORD | The proxy credential, verbatim | CURLOPT_PROXYUSERPWD is URL-decoded before use (a %25 becomes %), as is a credential embedded in the proxy URL. Verified against a local listener that printed the decoded Proxy-Authorization header |
CURLOPT_PROXYAUTH => CURLAUTH_BASIC | Send Basic on the first request | Node4's HTTP listeners challenge with Proxy-Authenticate: Basic realm="node4"; CURLAUTH_ANY would spend a round trip asking |
CURLOPT_NOPROXY => '' | Proxy every host | A no_proxy variable in the environment is honored even when CURLOPT_PROXY is set in code; the empty string cancels it |
CURLOPT_PROXY => '' | Go direct | An empty proxy string disables the environment's https_proxy too, which makes the direct half of the comparison trustworthy |
CURLOPT_HTTPPROXYTUNNEL | Force a CONNECT tunnel for everything | Not set. HTTPS targets are tunneled anyway; setting it for http:// targets hides the gateway's response headers behind a tunnel for no gain |
CURLOPT_CONNECTTIMEOUT, CURLOPT_TIMEOUT | Time for the connection phase; time for the whole transfer | Example values. The connection phase is everything until the connection to the target is usable: resolving and reaching the proxy, the CONNECT or SOCKS5 exchange, and the TLS handshake with the target through the tunnel. CURLOPT_TIMEOUT covers the whole transfer, connection phase included |
CURLOPT_SSL_VERIFYPEER, CURLOPT_SSL_VERIFYHOST | Verify the target's certificate | Left on. An HTTP proxy relays the TLS bytes it cannot read; disabling verification fixes nothing about the proxy |
CURLOPT_FOLLOWLOCATION => false | Do not follow redirects | A redirect is something to inspect before the next request leaves through the same exit |
The username and password are separate values, so a credential of any shape works without encoding. If you prefer one user:pass string in CURLOPT_PROXYUSERPWD, pass rawurlencode($user) . ':' . rawurlencode($pass). If you prefer the credential inside the proxy URL, the same encoding applies there; that is the form Guzzle uses, below.
SOCKS5: CURLPROXY_SOCKS5_HOSTNAME, not CURLPROXY_SOCKS5
Switch the scheme and nothing else:
$proxyUrl = 'socks5h://gw-rotating_datacenter.node4.io:1083';Or spell the type out:
CURLOPT_PROXY => 'gw-rotating_datacenter.node4.io:1083',
CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5_HOSTNAME,CURLPROXY_SOCKS5 and CURLPROXY_SOCKS5_HOSTNAME authenticate the same way, with the SOCKS5 username and password exchange that libcurl offers by default (CURLOPT_SOCKS5_AUTH needs no change), and they differ in one thing: who resolves the target hostname. CURLPROXY_SOCKS5 resolves it on your machine and sends the proxy an IP address; CURLPROXY_SOCKS5_HOSTNAME (socks5h://) sends the hostname and the exit resolves it. The second keeps your resolver out of the picture and gets you the DNS answer the exit would get, which matters for geo-fenced DNS and for any target whose records differ by region. The same choice exists on the command line, covered in curl SOCKS5 vs HTTP proxy.
Country and session segments in the username work identically over SOCKS5, because the gateway reads the same username. What changes is how a refusal looks. Here is the SOCKS5 run with the wrong credential:
proxied: socks5-not-allowed errno=97 connect=0 status=0 error=cannot complete SOCKS5 connection to node4.io. (2)SOCKS5 has no status line and no headers, so the gateway accepts the credential exchange and then refuses the connection request with a reply byte, the number in parentheses. Reply 2 ("connection not allowed by ruleset") covers every cause a 407 covers and also a Rotating Unmetered account at its connection ceiling, so on its own it does not prove a bad credential; 4 is the country refusal and 1 the sticky-session failure. socks5_cause() keeps each reply apart (and the replies 3 and 5 a target network can produce), reading the CURLPX_* value on PHP 8.2 and later and the reply byte on older builds. The table in the 407 section below maps them. To learn why a SOCKS5 connection was refused, repeat the same request over the HTTP port, where the answer has a status and a body.
Verify the exit, not the status
Three checks, in order:
- Compare addresses. The
directandproxiedlines ofrun.phpmust differ.CURLINFO_PRIMARY_IPdoes not help here: in a proxied transfer it is the address of the gateway you connected to, not the exit the target saw. - Read the country. The echo endpoint's
countryfield is the exit's country. With no-country-segment, a rotating datacenter exit is in the US, Italy or Spain; with-country-itit isITor the request is refused, never served from elsewhere. - Check the content, then the headers. A 200 can carry a consent page or a login form. Validate a field your parser needs before treating the response as data. For diagnosis the gateway adds
X-Node4-Sticky(opened,held,noneorunavailable) to plain-HTTP responses and to theCONNECT200 line, andX-Node4-Country(honored,unavailable,none) to plain-HTTP responses and to refusals. libcurl handsCONNECTresponse headers to your header callback unlessCURLOPT_SUPPRESS_CONNECT_HEADERSis set. The callback starts a new block at each status line, so theCONNECTanswer stays in its own block andgateway_headers()readsx-node4-stickyfrom it; a target that sends a header of the same name cannot overwrite the gateway's value. On a successful HTTPS tunnel the country header is absent, so prove the country by the echo endpoint, not by the header. SOCKS5 carries neither header.
Rotation, sticky sessions and connection reuse
A rotating gateway picks an exit per connection: a new CONNECT tunnel, a new SOCKS5 connection, or a new plain-HTTP request. proxy_fetch creates and closes a handle per call, so each call is a new connection and can leave from a different exit. If you reuse one handle across calls, libcurl keeps the tunnel open and every request down it leaves from the same exit; to force a new exit per request on a reused handle set CURLOPT_FORBID_REUSE => true, which closes the connection after each transfer. The timing rules are in how often the rotating IP changes.
To hold one exit across requests on purpose, add a session id to the username:
$username = gateway_username('USERNAME', null, 'job4182'); // USERNAME-session-job4182
$username = gateway_username('USERNAME', 'us', 'job4182'); // USERNAME-country-us-session-job4182On the rotating gateways a session id pins one exit for up to 30 minutes from the moment it is first assigned, and activity does not extend the window, so work that outlives it should mint a new id and continue. The id is yours to invent. The gateway reads whatever sits between -session- and the next marker, so the builder keeps it to 1 to 32 letters and digits, the shape the dashboard's own builder produces, and a hyphen inside an id can never start a segment. The id is scoped to your credential, so another customer's job4182 is unrelated to yours. A country segment narrows the candidates; a session pins the choice. When to use one at all, and what breaks when an exit changes mid-task, is covered in sticky vs rotating sessions.
The builder's validation exists because the gateway parses the username by markers and never reports a typo as a typo. A misspelled key straight after the username (USERNAME-sesion-x) leaves the whole string as the username, which matches no credential: a 407. A misspelled key after -country- becomes part of the country value (US-SESION-X), which has no exits: a 502. A misspelled key after -session- becomes part of the session id, and the request is served from an untargeted exit with no error at all. The typo examples walk through each case. The residential gateway is stricter: a misspelled key is a 400 that names it wherever it sits, and its sessions have a 30-minute ceiling with no minimum, because the exit is a consumer device; the segment grammar for state, city and asn is in country and city targeting.
IP whitelisting is the alternative to the credential and works on every product: register the address under Auth & IP Access and connect with no credentials, or on the rotating gateways send the username with an empty password (CURLOPT_PROXYPASSWORD => '') to keep country and session targeting, while a whitelisted residential connection carries no username and is therefore untargeted. Authentication covers which to use where.
Guzzle: the proxy option
Guzzle's curl handler passes the proxy option to libcurl as CURLOPT_PROXY, so everything above about schemes and refusals holds. A string applies to every target scheme; an array keys a proxy by target scheme (http, https) and takes a no list of hosts to leave unproxied. The credential travels inside the URL, where libcurl URL-decodes it, so percent-encode both halves. Save this as guzzle_fetch.php next to proxy_fetch.php (for socks5_cause()) and a composer require guzzlehttp/guzzle:
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/proxy_fetch.php'; // socks5_cause()
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\TransferException;
/** scheme is "http" or "socks5h"; the username may carry -country- and -session- segments. */
function proxy_url(string $scheme, string $host, int $port, string $username, string $password): string
{
return sprintf('%s://%s:%s@%s:%d', $scheme, rawurlencode($username), rawurlencode($password), $host, $port);
}
function guzzle_fetch(Client $client, string $url, string $proxyUrl): array
{
try {
$response = $client->get($url, ['proxy' => $proxyUrl]);
$status = $response->getStatusCode();
if ($status === 407) {
return ['cause' => 'proxy-auth', 'status' => 407, 'body' => (string) $response->getBody()];
}
return ['cause' => $status < 300 ? 'ok' : 'target-http-' . $status, 'status' => $status, 'body' => (string) $response->getBody()];
} catch (BadResponseException $e) { // only with http_errors left on
return ['cause' => 'target-http-' . $e->getResponse()->getStatusCode(), 'status' => $e->getResponse()->getStatusCode(), 'body' => ''];
} catch (TransferException $e) { // Guzzle 7: RequestException or ConnectException; Guzzle 8: NetworkException
$message = $e->getMessage();
$cause = match (true) {
(bool) preg_match('/CONNECT tunnel failed, response (\d{3})/', $message, $m) => $m[1] === '407' ? 'proxy-auth' : 'proxy-refused-' . $m[1],
str_contains($message, 'cURL error 97') => socks5_cause(0, $message), // the reply byte is in the message
str_contains($message, 'cURL error 28') => 'timeout',
str_contains($message, 'cURL error 5:'),
str_contains($message, 'cURL error 7:') => 'proxy-unreachable',
default => get_class($e),
};
return ['cause' => $cause, 'status' => 0, 'body' => '', 'error' => $message];
}
}
$client = new Client([
'connect_timeout' => 10,
'timeout' => 30,
'allow_redirects' => false,
'http_errors' => false, // a 407 or a 502 comes back as a response to inspect, not an exception
]);
$host = 'gw-rotating_datacenter.node4.io';
$user = getenv('NODE4_PROXY_USER') ?: '';
$pass = getenv('NODE4_PROXY_PASS') ?: '';
$echo = 'https://node4.io/api/tools/ip';
$cases = [
'HTTP proxy, HTTPS target' => [proxy_url('http', $host, 8083, $user, $pass), $echo],
'HTTP proxy, HTTP target' => [proxy_url('http', $host, 8083, $user, $pass), 'http://httpbin.org/ip'],
'SOCKS5h proxy, HTTPS target' => [proxy_url('socks5h', $host, 1083, $user, $pass), $echo],
'sticky session job4182' => [proxy_url('http', $host, 8083, $user . '-session-job4182', $pass), $echo],
];
foreach ($cases as $label => [$proxyUrl, $url]) {
$r = guzzle_fetch($client, $url, $proxyUrl);
$detail = isset($r['error']) ? (strstr($r['error'], ' (see ', true) ?: $r['error']) : trim($r['body']); // drop Guzzle's "(see https://curl.se/...)" tail
printf("%-28s cause=%-18s status=%d %s\n", $label, $r['cause'], $r['status'], substr($detail, 0, 70));
}Expected result: four ok lines, the first, third and fourth showing an exit address from the echo endpoint and the second showing httpbin's origin. With the wrong credential the run prints, identically on Guzzle 7.17 and 8.6:
HTTP proxy, HTTPS target cause=proxy-auth status=0 cURL error 56: CONNECT tunnel failed, response 407
HTTP proxy, HTTP target cause=proxy-auth status=407 proxy authentication required
SOCKS5h proxy, HTTPS target cause=socks5-not-allowed status=0 cURL error 97: cannot complete SOCKS5 connection to node4.io. (2)
sticky session job4182 cause=proxy-auth status=0 cURL error 56: CONNECT tunnel failed, response 407Four things about Guzzle that the libcurl section does not tell you:
- The exception class changed between major versions. A refused
CONNECTis aGuzzleHttp\Exception\RequestExceptionon Guzzle 7, and$e->getResponse()on it carries the 407. On Guzzle 8 it is aGuzzleHttp\Exception\NetworkException, which has no response and no handler context, because Guzzle 8 setsCURLOPT_SUPPRESS_CONNECT_HEADERSand the 407's headers never reach it; the curl error number and theCONNECTstatus are in the message only. Both extendTransferException, so catch that and read the message. A connect timeout is aConnectException(or a subclass of it) on both versions; a proxy hostname that does not resolve (cURL error 5) and a SOCKS5 refusal are aRequestExceptionon 7 and aConnectExceptionon 8. http_errorsdecides what a plain-HTTP 407 is. Left on, Guzzle throwsClientExceptionfor it; off, as above, it is a response with status 407 you can branch on. Either way a 407 on an HTTPS target is the exception path, because libcurl never produced a response.- A sticky session is a per-request
proxystring. The session id lives in the proxy username, so each session is a different proxy URL. Pass it per request, asguzzle_fetchdoes, rather than building one client per session. socks5h://works. Guzzle hands the string to libcurl, which speaks SOCKS5 natively (Guzzle 8 first checks the proxy scheme against the six its cURL handler accepts, andsocks5his one of them); no extra package is needed. The refusal in the third line is the same reply2the raw cURL run produced.
When no proxy option is given, Guzzle reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY from the environment. When you do pass one, the no list is yours to supply, and a stale NO_PROXY in a container does not apply. Guzzle's own description of the option is in the request options reference.
407, 502 and timeouts: what PHP shows and what to change
Each failure as it looks from inside PHP, where to read it, and what to change. The gateway's answer and the target's answer are separate columns of evidence: CURLINFO_HTTP_CONNECTCODE is the gateway's reply to CONNECT, and once that is 200 every later status is the target's. A country refusal reaches PHP the same way a 407 does: curl_errno 56 with the code in CURLINFO_HTTP_CONNECTCODE on an HTTPS target, an ordinary response on a plain-HTTP one. The curl error numbers are libcurl's and are listed on libcurl-errors.
What proxy_fetch reports | Where the detail is | Cause | What to change |
|---|---|---|---|
proxy-auth, errno=56 (or 7 on newer libcurl), connect=407, "CONNECT tunnel failed, response 407" | CURLINFO_HTTP_CONNECTCODE | The proxy refused the credential: a wrong or stale pair, an invisible character from a paste, a whitelisted address that changed, a free or lapsed account on a gateway, an allowance used up, or a misspelled key straight after the username | Reproduce with the one-line curl command. If curl works, the bug is in how PHP passes the credential; if not, work through the seven causes of a 407 |
proxy-auth, status=407, body proxy authentication required | CURLINFO_RESPONSE_CODE on an http:// target | Same as above | Same as above |
proxy-refused-502, connect=502; on plain HTTP a 502 whose body begins no exit available | Connect code, or the gateway's body on plain HTTP | A -country- code with no exits, or a typo after -country- that became part of the code | Fix the code or drop the segment. Retrying cannot help |
target-http-502, connect=200 (or a plain-HTTP 502 without the gateway's body) | $result['status'] | The tunnel opened; the target or its own upstream answered 502 | Treat it as the target's error: retry later or check the target. Changing the country or the credential does not help |
proxy-refused-503, connect=503 on HTTPS; on plain HTTP a 503 with X-Node4-Sticky: unavailable and body sticky session unavailable | The connect code on HTTPS, the header and body on plain HTTP | The gateway cannot pin an exit right now | Retry after a pause, or drop -session- to accept rotation |
proxy-refused-429, connect=429; on plain HTTP a 429 with X-Node4-Conn-Limit and body beginning connection limit reached | Connect code, or the header on plain HTTP | The account already holds every concurrent connection its Rotating Unmetered plan allows | Back off, close idle connections (pooled ones count), lower $concurrency in the worker below, or move to a higher rung (connection limits) |
socks5-not-allowed, errno=97, error ends (2) | CURLINFO_PROXY_ERROR = CURLPX_REPLY_NOT_ALLOWED | Every 407 cause, plus a Rotating Unmetered account at its connection ceiling | Repeat one request over the HTTP port: a 407 is the credential, a 429 the ceiling. Until you know, back off rather than stop |
socks5-auth-rejected, errno=97 | CURLINFO_PROXY_ERROR = CURLPX_USER_REJECTED | The proxy rejected the username and password exchange itself | Fix the credential; Node4's gateways answer a wrong credential with reply 2 instead |
socks5-host-unreachable, errno=97, error ends (4) | CURLINFO_PROXY_ERROR = CURLPX_REPLY_HOST_UNREACHABLE | A country with no exits over SOCKS5, or the exit could not reach the target | As for 502; if untargeted, retry with a new connection |
socks5-unavailable, errno=97, error ends (1) | CURLINFO_PROXY_ERROR = CURLPX_REPLY_GENERAL_SERVER_FAILURE | The SOCKS5 form of the 503 above: the session cannot be pinned right now | Retry, or drop -session- |
socks5-network-unreachable or socks5-connection-refused, error ends (3) or (5) | CURLINFO_PROXY_ERROR = CURLPX_REPLY_NETWORK_UNREACHABLE or CURLPX_REPLY_CONNECTION_REFUSED | The exit could not reach the target, or the target refused it | Check the target host and port; not a credential problem |
timeout, errno=28 | CURLINFO_CONNECT_TIME (0: the gateway was never reached), the connect code (0 after reaching it: stuck in the CONNECT or SOCKS5 exchange), CURLINFO_APPCONNECT_TIME (0 with connect=200: stuck in the TLS handshake with the target) | CURLOPT_CONNECTTIMEOUT expired somewhere in the connection phase, or CURLOPT_TIMEOUT expired on the whole transfer, for example a target slow to answer | Identify the stage first; these timings are also 0 on a reused connection, so read them on a fresh one. A larger timeout does not repair a wrong port or a target that never answers |
proxy-unreachable, errno=5 or 7 with connect=0 (an errno 7 with connect=407 is the proxy-auth row) | curl_error: "Could not resolve proxy" or "Failed to connect" | Hostname typo, wrong port, or an outbound firewall | Check the host and port against the table above |
curl-60 | curl_error | The target's certificate did not verify | Check the clock and the CA bundle (curl.cainfo in php.ini). Do not set CURLOPT_SSL_VERIFYPEER to false |
ok, wrong content | The body | The target served a login, consent or challenge page | Validate a page-specific marker; a 200 is not a result |
target-http-403 or -429 with no X-Node4-Conn-Limit header | $result['status'] | The target refused or rate-limited the exit | A 429 wants less pressure and Retry-After, not a new credential. Why an IP gets blocked |
A queue worker with curl_multi
Once one request passes every check, run many. curl_multi keeps a bounded number of transfers in flight without threads, and the design choices below are the ones a proxy adds. Each attempt uses one session id, so every request of that attempt leaves from one exit; a retry salts the id, which starts a new session, so a later attempt may leave from another exit (or draw the same address again, which is not a fault). A job that must keep its cookies or location across retries should keep its original session id instead and handle the session ending. The worker stops the whole queue only on a credential refusal, because every job shares the credential; a connection-ceiling refusal or a busy exit gets a bounded retry with backoff. Save this as worker.php beside proxy_fetch.php:
<?php
declare(strict_types=1);
require __DIR__ . '/proxy_fetch.php'; // gateway_username(), proxy_options(), classify_result()
$proxyUrl = getenv('NODE4_PROXY_URL') ?: null; // null runs the queue direct, for comparison
$baseUser = getenv('NODE4_PROXY_USER') ?: '';
$password = getenv('NODE4_PROXY_PASS') ?: '';
$concurrency = 4; // open connections, idle ones included, not only active transfers
$maxAttempts = 3;
$stopOn = ['proxy-auth', 'socks5-auth-rejected']; // the credential itself was refused: no job can succeed
$retryOn = ['proxy-refused-429', 'proxy-refused-503', 'socks5-not-allowed', 'socks5-unavailable',
'socks5-host-unreachable', 'timeout']; // pressure or a busy exit: back off, then try a new session
$backoff = fn (int $attempt): float => min(30, 2 ** $attempt) + mt_rand(0, 1000) / 1000; // 4 s, 8 s, plus jitter
$queue = [];
foreach (['a', 'b', 'c', 'd', 'e', 'f'] as $i) {
$queue[] = ['id' => 'job' . $i, 'url' => 'https://node4.io/api/tools/ip', 'attempt' => 1, 'not_before' => 0.0];
}
$mh = curl_multi_init();
curl_multi_setopt($mh, CURLMOPT_MAX_TOTAL_CONNECTIONS, $concurrency); // a hard ceiling on open sockets
$active = []; // spl_object_id(handle) => ['job' => ..., 'blocks' => ...]
$results = [];
$stop = null; // the cause that stopped the queue, if one did
$start = function (array $job) use ($mh, &$active, $proxyUrl, $baseUser, $password): void {
// one session id per attempt: a retry salts it, so it starts a new session
$session = $job['attempt'] > 1 ? $job['id'] . 'a' . $job['attempt'] : $job['id'];
$username = $proxyUrl === null ? '' : gateway_username($baseUser, null, $session);
$blocks = [];
$ch = curl_init($job['url']);
curl_setopt_array($ch, proxy_options($proxyUrl, $username, $password, $blocks));
curl_setopt($ch, CURLOPT_FORBID_REUSE, true); // every attempt has its own username, so an idle tunnel is never reused
$active[spl_object_id($ch)] = ['job' => $job, 'blocks' => &$blocks];
curl_multi_add_handle($mh, $ch);
};
do {
$now = microtime(true);
foreach ($queue as $k => $job) {
if ($stop !== null || count($active) >= $concurrency) {
break;
}
if ($job['not_before'] <= $now) {
unset($queue[$k]);
$start($job);
}
}
curl_multi_exec($mh, $running);
if ($running) {
curl_multi_select($mh, 1.0);
} elseif ($active === [] && $queue !== [] && $stop === null) {
usleep(200_000); // only backed-off jobs are waiting
}
while ($info = curl_multi_info_read($mh)) {
$ch = $info['handle'];
$slot = $active[spl_object_id($ch)];
unset($active[spl_object_id($ch)]);
$job = $slot['job'];
$body = curl_multi_getcontent($ch);
$r = classify_result($ch, $info['result'], is_string($body) ? $body : '', $slot['blocks']); // $info['result'] is the errno
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
if (in_array($r['cause'], $stopOn, true)) {
$stop = $r['cause']; // fix the credential, then rerun
} elseif (in_array($r['cause'], $retryOn, true) && $job['attempt'] < $maxAttempts) {
$job['attempt']++;
$job['not_before'] = microtime(true) + $backoff($job['attempt']);
$queue[] = $job; // bounded retry, later, with a new session id
continue;
}
$exit = $r['cause'] === 'ok' ? (json_decode($r['body'], true)['ip'] ?? '?') : '-';
$results[] = ['cause' => $r['cause'], 'line' => sprintf("%s attempt=%d %-18s exit=%-15s sticky=%s",
$job['id'], $job['attempt'], $r['cause'], $exit, $r['gateway_headers']['x-node4-sticky'] ?? 'n/a')];
}
} while ($running || $active !== [] || ($stop === null && $queue !== []));
curl_multi_close($mh);
echo implode("\n", array_column($results, 'line')), "\n";
$failed = count(array_filter($results, fn (array $r): bool => $r['cause'] !== 'ok'));
if ($stop !== null) {
fwrite(STDERR, "stopped: the proxy refused the credential ($stop); " . count($queue) . " job(s) left in the queue\n");
exit(1);
}
if ($failed > 0) {
fwrite(STDERR, "$failed job(s) failed after retries; for socks5-not-allowed, repeat one request over the HTTP port to tell a 407 from a 429\n");
exit(2);
}Expected result: six lines, one per job, each ok with an exit address, and exit status 0. Run with NODE4_PROXY_URL unset, every line shows your own address, which is the direct comparison. With a credential refused over the HTTP port the worker prints four proxy-auth lines (the four that were in flight), writes stopped: the proxy refused the credential (proxy-auth); 2 job(s) left in the queue to stderr and exits 1, so a scheduler sees the failure instead of a queue that quietly drained into errors. Over SOCKS5 the same refusal is reply 2, which the gateway also sends at the connection ceiling, so the worker retries each job with backoff up to $maxAttempts times, reports what is still failing, and exits 2 with the pointer to the HTTP-port check.
Three details that bite in curl_multi code. curl_errno($ch) is not the error for a multi transfer; $info['result'] from curl_multi_info_read is, and curl_multi_getcontent is how you read a body when CURLOPT_RETURNTRANSFER is on. Removing and closing an easy handle does not close its connection: the multi handle keeps it in its pool for reuse, so without the two settings above a loop of four transfers can hold more than four open tunnels. CURLMOPT_MAX_TOTAL_CONNECTIONS caps every connection the multi handle has open, idle ones included, and CURLOPT_FORBID_REUSE closes each tunnel when its transfer ends, which costs a new handshake per attempt but nothing here, since each attempt's username differs and a pooled tunnel could not be reused anyway. A worker that sends every job with one username can drop CURLOPT_FORBID_REUSE to save handshakes and rely on the cap alone. All of this matters on Rotating Unmetered, which is priced by concurrent connections: the ceiling you buy counts every open connection on the account, idle tunnels included, from this worker and from any other process or client using the same plan, so set $concurrency to your share of it (connection limits).
Where this is the wrong tool
- The page needs JavaScript. PHP cURL fetches what the server sends. A page assembled in the browser needs a browser; Puppeteer and Playwright through a proxy covers credentials there.
- The target must see one address for weeks. A rotating gateway cannot promise that, and a session id holds an exit for minutes. Use a static dedicated datacenter proxy, whose address stays the same for as long as the plan is paid, with no data cap, and whose host and port drop into
CURLOPT_PROXYwith no username segments. - Datacenter ranges are classified by your target. Serious anti-bot targets do that, and no PHP option changes it. The residential gateway takes the same code with the host and port from the table above and a stricter targeting grammar.
- You need UDP over SOCKS5. The gateways carry TCP only.
UDP ASSOCIATEis available on request on US shared and dedicated datacenter IPs, as the SOCKS5 support page describes. - You have not bought a plan yet. The free tier cannot reach the gateways or SOCKS5, so a gateway test needs a paid plan, from the rotating proxies page. It can still run the HTTP path of
proxy_fetchagainst a static shared proxy, which proves the credential handling before you pay.
Translating a working curl command into these options by hand is where the proxy flag most often gets dropped. The curl converter emits the PHP equivalent of a curl -x command, and the proxy connection builder turns a protocol, host, port and credential into the scheme://username:password@host:port string and curl, Python, Node.js and Scrapy snippets, a quick cross-check of the string PHP should be sending.
FAQ
How do I use a proxy with PHP cURL?
Set CURLOPT_PROXY to http://HOST:PORT, and for an authenticated proxy add CURLOPT_PROXYUSERNAME and CURLOPT_PROXYPASSWORD. Nothing else changes for an https:// target: libcurl opens the CONNECT tunnel and verifies the target's certificate through it.
Why does PHP cURL return false with "CONNECT tunnel failed, response 407"?
The proxy refused your credential while the HTTPS tunnel was being set up, so there is no response object; curl_errno is 56 (7 on newer libcurl builds) and curl_getinfo($ch, CURLINFO_HTTP_CONNECTCODE) is 407. Read the connect code, not the errno, to tell this apart from an unreachable proxy. Check the credential with a one-line curl command before changing PHP.
Should I use CURLOPT_PROXYUSERPWD or CURLOPT_PROXYUSERNAME and CURLOPT_PROXYPASSWORD?
The separate options take the values verbatim. CURLOPT_PROXYUSERPWD is URL-decoded, so a password containing % or : must be percent-encoded in it or the proxy receives a different password.
How do I use a SOCKS5 proxy in PHP cURL?
Use the socks5h:// scheme in CURLOPT_PROXY, or set CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, with the same username and password options. CURLPROXY_SOCKS5 resolves the target hostname on your machine instead of at the exit; prefer the hostname variant.
Does Guzzle support SOCKS5 proxies?
Yes. Guzzle passes the proxy option to libcurl, so 'proxy' => 'socks5h://user:pass@host:port' works on Guzzle 7 and 8 with no extra package. A refusal arrives as a TransferException whose message contains cURL error 97.
Do I need CURLOPT_HTTPPROXYTUNNEL?
Not for HTTPS targets, which libcurl tunnels anyway. It forces a CONNECT tunnel for plain http:// targets, which hides the gateway's response headers you would otherwise read for diagnosis.
How do I get a different IP on each connection in PHP?
The rotating gateway picks the exit per connection (per request only for a plain http:// target through the HTTP port), so for HTTPS targets open a new connection for each call: a new handle per call does that, and on a reused handle CURLOPT_FORBID_REUSE => true closes the connection after each transfer. Each new connection is a new pick, so the same address can come back. To hold one exit on purpose, add -session-<id> to the username instead; in the worker above that is one session per attempt, and a retry starts a new one.
Related guides
- Authenticating curl through a proxy, the one-line command to reproduce any failure above outside PHP
- curl SOCKS5 vs HTTP proxy workflow, the same
socks5h://choice and a protected config file for unattended jobs - Go net/http proxy authentication and Java HttpClient proxy authentication, the same workflow in two languages whose standard clients handle
CONNECTdifferently - Node.js production-ready proxy rotation, the worker pattern above with agents instead of
curl_multi - SOCKS5 proxy setup, the port for each product and the
socks5hexplanation for curl, Python and Node