Sending PHP cURL Requests Through an Authenticated Proxy
By the ProxyV4 Engineering Team · Updated:
To use a proxy with PHP cURL, set CURLOPT_PROXY to the proxy address and CURLOPT_PROXYUSERPWD to user:pass on the handle before you call curl_exec(). Below you will find working snippets for each case, a way to confirm the exit IP, and what the common cURL error numbers actually mean.
A working PHP cURL proxy request
The script below sends one HTTPS request through an HTTP proxy with a username and password, then prints the IP address the target saw. Replace PORT, USER and PASS with the values from your proxy line. If your provider hands you ip:port:user:pass, the proxy format converter can rewrite a whole list into URL form.
<?php
$ch = curl_init('https://proxyv4.com/api/my-ip');
curl_setopt_array($ch, [
CURLOPT_PROXY => 'http://203.0.113.10:PORT',
CURLOPT_PROXYUSERPWD => 'USER:PASS',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
]);
$body = curl_exec($ch);
if ($body === false) {
fwrite(STDERR, 'cURL error ' . curl_errno($ch) . ': ' . curl_error($ch) . PHP_EOL);
exit(1);
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($body, true);
echo "HTTP $status, exit IP: {$data['ip']}" . PHP_EOL;If the output shows your server's own IP, the proxy option never reached this handle.
The options that control the proxy
Only a handful of CURLOPT_ constants matter for proxying.
CURLOPT_PROXY: host, host:port or a full URL. The scheme prefix (http://,socks5://,socks5h://) picks the protocol; with no prefix, cURL assumes an HTTP proxy.CURLOPT_PROXYUSERPWD:user:passsent to the proxy. This is separate fromCURLOPT_USERPWD, which goes to the target site.CURLOPT_PROXYTYPE: the protocol as a constant, used whenCURLOPT_PROXYhas no scheme.CURLOPT_NOPROXY: a comma-separated list of hosts that bypass the proxy,*to bypass it for everything.CURLOPT_HTTPPROXYTUNNEL: forces aCONNECTtunnel even for plainhttp://targets. HTTPS targets are always tunneled, so you rarely need it.
Passwords with colons or symbols
CURLOPT_PROXYUSERPWD splits on the first colon, so a username containing : breaks it. Set the two halves separately instead, which also avoids any URL-encoding concerns:
curl_setopt($ch, CURLOPT_PROXYUSERNAME, 'USER');
curl_setopt($ch, CURLOPT_PROXYPASSWORD, 'p@ss:with:colons');When you put credentials inside a proxy URL (for Guzzle or an environment variable), percent-encode reserved characters, for example with rawurlencode(), or the URL parser will cut the password short.
PHP cURL SOCKS5 proxy setup
libcurl speaks SOCKS5 natively, including username and password login, so PHP needs no extension or package beyond the standard cURL module. You switch protocols by changing the scheme in CURLOPT_PROXY; the credential option stays the same.
<?php
$ch = curl_init('https://proxyv4.com/api/my-ip');
curl_setopt_array($ch, [
// socks5h: the proxy resolves the target hostname
CURLOPT_PROXY => 'socks5h://203.0.113.10:PORT',
CURLOPT_PROXYUSERPWD => 'USER:PASS',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
]);
echo curl_exec($ch) ?: curl_error($ch);If you prefer keeping the host and port separate, the constant form does the same job. CURLPROXY_SOCKS5_HOSTNAME is the constant equivalent of the socks5h:// prefix:
curl_setopt($ch, CURLOPT_PROXY, '203.0.113.10');
curl_setopt($ch, CURLOPT_PROXYPORT, PORT);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'USER:PASS');socks5:// versus socks5h://
With socks5:// (or CURLPROXY_SOCKS5), PHP's machine resolves the target hostname and sends the proxy a bare IP. With socks5h:// the hostname goes to the proxy and the proxy does the lookup. Use the h variant unless you have a reason not to: DNS answers then match the proxy's location.
Do you need SOCKS5 at all?
For HTTP and HTTPS requests, an HTTP proxy and a SOCKS5 proxy end up equivalent: both carry TLS end to end and the target sees the same exit IP. SOCKS5 matters when the code talks a non-HTTP protocol or when a tool only offers SOCKS. The HTTP vs SOCKS5 comparison covers the trade-offs in detail.
The Guzzle proxy option
Guzzle takes a proxy request option, either as a single URL or as an array keyed by scheme. Credentials go inside the URL. Set it in the client constructor to apply it to every request, or pass it to one call to override the default; an empty string turns the proxy off for that request.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$proxy = 'http://USER:[email protected]:PORT';
// Client-wide: every request from this client uses the proxy
$client = new Client([
'proxy' => $proxy,
'connect_timeout' => 10,
'timeout' => 30,
]);
$res = $client->get('https://proxyv4.com/api/my-ip');
echo $res->getBody() . PHP_EOL;
// Per request: overrides the client default for this call only
$res = $client->get('https://example.com/', ['proxy' => '']);The array form lets you route by target scheme and exclude hosts. Note that the https key still holds an http:// proxy URL: it describes which requests use the proxy, not how you talk to the proxy.
$client = new Client([
'proxy' => [
'http' => 'http://USER:[email protected]:PORT',
'https' => 'http://USER:[email protected]:PORT',
'no' => ['localhost', '.internal.example'],
],
]);With Guzzle's default cURL handler, a socks5:// or socks5h:// URL in proxy works the same way as in raw cURL. The stream handler (used when the cURL extension is missing) only handles HTTP proxies.
Environment variables, PHP-FPM and which setting wins
libcurl reads proxy settings from the environment when the handle has no explicit proxy. The rules are stricter than most people expect:
http_proxyis read only in lowercase. libcurl deliberately ignoresHTTP_PROXY, because in CGI setups a request header calledProxybecomes that variable (the "httpoxy" issue).HTTPS_PROXY/https_proxyandALL_PROXY/all_proxywork in either case.NO_PROXY/no_proxylists hosts to skip, matched as domain suffixes.- An explicit
CURLOPT_PROXYalways beats the environment. Setting it to an empty string disables proxying even when variables are present.
CLI scripts and cron
A php worker.php run from a shell inherits the shell's variables, so export https_proxy=... works there. Cron starts jobs with a minimal environment, so either define the variables at the top of the crontab or, better, set CURLOPT_PROXY in code. Guzzle follows a similar policy: it reads HTTPS_PROXY and NO_PROXY, but uses HTTP_PROXY only under the CLI SAPI.
PHP-FPM workers
PHP-FPM pools default to clear_env = yes, so variables exported in your shell or systemd unit never reach the workers. Declare them in the pool file and reload the service:
; /etc/php/8.3/fpm/pool.d/www.conf (path varies by distro and PHP version)
env[https_proxy] = http://USER:[email protected]:PORT
env[no_proxy] = localhost,127.0.0.1WordPress and plugins behind one fixed IP
WordPress routes its HTTP API (wp_remote_get(), wp_remote_post(), update checks) through a proxy defined in wp-config.php. These constants are part of core:
// wp-config.php, above the "That's all, stop editing" line
define( 'WP_PROXY_HOST', '203.0.113.10' );
define( 'WP_PROXY_PORT', 'PORT' );
define( 'WP_PROXY_USERNAME', 'USER' );
define( 'WP_PROXY_PASSWORD', 'PASS' );
define( 'WP_PROXY_BYPASS_HOSTS', 'localhost, *.example.com' );Two limits apply. The constants configure an HTTP proxy only, so pick HTTP mode for this site. And plugins that call curl_init() directly instead of the WordPress HTTP API ignore these constants; check the plugin's code or settings page before assuming its traffic leaves through the proxy.
When a dedicated IPv4 helps PHP jobs
Typical PHP jobs that need a proxy: an API that only accepts calls from a registered address, a plugin pulling data from a partner who rate-limits per IP, or a price monitor that must behave consistently for weeks. Each wants one address that does not change and that nobody else uses.
That is what ProxyV4 private datacenter IPv4 is built for. Each IP has one tenant for the whole term, keeps the same address when you renew before expiry, and traffic is not metered, so a cron job that downloads large feeds does not create a surprise bill. Every proxy accepts username and password login over HTTP(S) and SOCKS5; from the order page you choose HTTP only, SOCKS5 only or both on the same port, and switching can move the proxy to a new port, so copy the line again afterwards.
It is the wrong fit if the target accepts only mobile carrier IPs, or if your job needs a fresh address on every request; rotating plans are not on sale. IPv6 proxies are sold separately, but private IPv4 reaches every IPv4 and dual-stack site. A sensible start is a single IP from the live pricing page: wire it into the real script, and scale once it behaves. A proxy that fails for a technical reason, such as not connecting or the wrong location, falls under the refund policy as account credit.
Reading cURL proxy errors in PHP
Log both curl_errno() and curl_error(). Wording shifts between libcurl versions, so match on the number in code.
Errno 5: Could not resolve proxy
cURL could not turn the proxy hostname into an address. Look for a typo, a stray http:// inside CURLOPT_PROXY combined with CURLOPT_PROXYPORT, or whitespace left over from reading the proxy line out of a file (use trim()).
Errno 7: Failed to connect
Nothing accepted the TCP connection at that IP and port. Common causes are a wrong port, a proxy switched between HTTP and SOCKS5 mode that now listens elsewhere, or an outbound firewall on the PHP host. Test the same values with the cURL command line from the same machine to separate PHP problems from network ones.
407 and CONNECT tunnel failures
For HTTPS targets a rejected login surfaces as errno 56 with text such as CONNECT tunnel failed, response 407 (older libcurl says Received HTTP code 407 from proxy after CONNECT). For plain http:// targets there is no cURL error: CURLINFO_HTTP_CODE simply returns 407. Check the credentials and the encoding of special characters; the 407 error guide lists the other causes. On SOCKS5, a bad password reads like User was rejected by the SOCKS5 server.
Errno 28: Operation timed out
Set CURLOPT_CONNECTTIMEOUT separately from CURLOPT_TIMEOUT so you can tell a proxy that never answered from a target that answered slowly. Without them a stuck connection can hold a PHP worker until max_execution_time kills it, or forever under the CLI, where that limit defaults to zero.
Frequently asked questions
What is the difference between CURLOPT_PROXYUSERPWD and CURLOPT_USERPWD?
CURLOPT_PROXYUSERPWD authenticates you to the proxy server. CURLOPT_USERPWD sends Basic auth to the destination website, so using it by mistake produces a 407 from the proxy.
Why does PHP cURL ignore my HTTP_PROXY variable?
libcurl only reads the lowercase http_proxy for plain HTTP, and PHP-FPM clears the environment by default. Set CURLOPT_PROXY in code or declare env[...] entries in the FPM pool.
Can I use a proxy with file_get_contents instead of cURL?
Yes, through a stream context with 'proxy' => 'tcp://IP:PORT', 'request_fulluri' => true and a Proxy-Authorization: Basic header you build yourself. It only handles HTTP proxies, so cURL or Guzzle is simpler for anything beyond a quick script.
Does one proxy work for both HTTP and SOCKS5 in PHP?
With ProxyV4 you can enable both on the same port from the order page, then pick http:// or socks5h:// in CURLOPT_PROXY without changing anything else. Changing the mode later can move the port, so recopy the proxy line.
How do I rotate between several proxies in a PHP script?
Keep the proxy URLs in an array and set CURLOPT_PROXY per handle, for example by index or at random. With curl_multi_* each handle can use a different proxy in parallel.
Run PHP jobs from a static IP
Get a private IPv4 that stays the same on renewal, with HTTP(S) and SOCKS5 login and unmetered traffic. Order one IP, plug it into CURLOPT_PROXY and scale when it works.
Order one IP