Skip to content
Guides 7 Connection Type: 1 views

PHP Proxy Setup

This guide covers PHP proxy setup with cURL, Guzzle, and file_get_contents. Efficiently integrate proxies for your web projects.

PHP proxy setup for cURL, Guzzle, and file_get_contents involves configuring HTTP client options or stream contexts to route outgoing requests through a specified proxy server, typically by defining the proxy's host, port, and authentication credentials.

Using a proxy server with PHP allows applications to mask their origin IP address, bypass geo-restrictions, access resources from internal networks, or manage request rates for web scraping and API interactions. The choice of method depends on the required control, complexity of requests, and error handling needs.

Using cURL

cURL is a robust library for making HTTP requests, offering extensive control over connection parameters, including proxy settings. It is a common choice for complex web interactions and is typically available as a PHP extension (php-curl).

Basic Proxy Setup

To route a request through an HTTP or HTTPS proxy, use CURLOPT_PROXY and CURLOPT_PROXYPORT.

<?php
$ch = curl_init();

// Target URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/data');

// Proxy settings
curl_setopt($ch, CURLOPT_PROXY, 'proxy.example.com');
curl_setopt($ch, CURLOPT_PROXYPORT, 8080);

// Return the transfer as a string instead of outputting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>

SOCKS Proxy

cURL supports SOCKS proxies (SOCKS4, SOCKS4a, SOCKS5, SOCKS5h). Specify the proxy type using CURLOPT_PROXYTYPE.

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// SOCKS5 proxy settings
curl_setopt($ch, CURLOPT_PROXY, 'socks5.example.com');
curl_setopt($ch, CURLOPT_PROXYPORT, 1080);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // Or CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A, CURLPROXY_SOCKS5_HOSTNAME

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>

Proxy with Authentication

For proxies requiring authentication, use CURLOPT_PROXYUSERPWD with a username:password string.

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Proxy settings with authentication
curl_setopt($ch, CURLOPT_PROXY, 'authproxy.example.com');
curl_setopt($ch, CURLOPT_PROXYPORT, 8080);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'proxyuser:proxypassword');

// Optional: Specify proxy authentication method (e.g., CURLAUTH_BASIC, CURLAUTH_DIGEST)
// curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>

HTTPS Proxy (CONNECT Tunneling)

When connecting to an HTTPS target through an HTTP proxy, cURL uses the HTTP CONNECT method to establish a tunnel. CURLOPT_HTTPPROXYTUNNEL can explicitly enable this, though it's often handled automatically.

<?php
$ch = curl_init();

// Target HTTPS URL
curl_setopt($ch, CURLOPT_URL, 'https://secure.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Proxy settings
curl_setopt($ch, CURLOPT_PROXY, 'proxy.example.com');
curl_setopt($ch, CURLOPT_PROXYPORT, 8080);

// Enable tunneling for HTTPS through HTTP proxy (often implied)
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);

// Handle SSL certificate verification (disable for testing, enable for production)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>

Common cURL Options for Proxies

  • CURLOPT_TIMEOUT: Maximum time in seconds for the cURL operation.
  • CURLOPT_CONNECTTIMEOUT: Maximum time in seconds to establish a connection.
  • CURLOPT_FOLLOWLOCATION: Follow any Location: HTTP headers.
  • CURLOPT_MAXREDIRS: Maximum number of redirects to follow.
  • CURLOPT_SSL_VERIFYPEER, CURLOPT_SSL_VERIFYHOST: Control SSL certificate verification. Set to true for production.
  • CURLOPT_HEADER: Include the header in the output.

Using Guzzle

Guzzle is a popular PHP HTTP client that provides a higher-level abstraction over cURL, simplifying common HTTP tasks. It requires installation via Composer.

Basic Proxy Setup

Guzzle clients and requests accept a proxy option. This can be defined globally for a client or per-request.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client([
    // Base URI for all requests made with this client
    'base_uri' => 'http://example.com/',
    // Global proxy setting for the client
    'proxy' => 'http://proxy.example.com:8080',
]);

try {
    $response = $client->request('GET', 'api/data');
    echo $response->getBody();
} catch (GuzzleHttp\Exception\RequestException $e) {
    echo 'Guzzle error: ' . $e->getMessage();
}
?>

Proxy with Authentication

Include authentication credentials directly in the proxy URI for HTTP/HTTPS proxies.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'http://example.com/',
    // Proxy with authentication
    'proxy' => 'http://proxyuser:proxypassword@authproxy.example.com:8080',
]);

try {
    $response = $client->request('GET', 'api/data');
    echo $response->getBody();
} catch (GuzzleHttp\Exception\RequestException $e) {
    echo 'Guzzle error: ' . $e->getMessage();
}
?>

SOCKS Proxy

Specify SOCKS proxies using the socks scheme in the proxy URI.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'http://example.com/',
    // SOCKS5 proxy
    'proxy' => 'socks5://socks5.example.com:1080',
]);

try {
    $response = $client->request('GET', 'api/data');
    echo $response->getBody();
} catch (GuzzleHttp\Exception\RequestException $e) {
    echo 'Guzzle error: ' . $e->getMessage();
}
?>

Per-Request Proxies

The proxy option can be overridden or specified for individual requests.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client(); // No global proxy

try {
    $response = $client->request('GET', 'http://example.com/api/data', [
        'proxy' => 'http://perrequestproxy.example.com:8080', // Proxy for this specific request
    ]);
    echo $response->getBody();
} catch (GuzzleHttp\Exception\RequestException $e) {
    echo 'Guzzle error: ' . $e->getMessage();
}
?>

Common Guzzle Options for Proxies

  • proxy: The proxy URI string (http://, https://, socks4://, socks5://).
  • verify: Controls SSL certificate verification (true, false, or path to CA bundle).
  • timeout: Total timeout for the request in seconds.
  • connect_timeout: Timeout for connecting to the server in seconds.
  • allow_redirects: Controls redirect handling (true, false, or array of options).

Using file_get_contents

file_get_contents is a simple function for reading file contents, including URLs. It can use stream contexts to configure proxy settings, but offers less control and error handling compared to cURL or Guzzle. It is suitable for basic HTTP/HTTPS requests with simple proxy requirements.

Basic Proxy Setup

Use stream_context_create to define proxy settings within the http options.

<?php
$proxy = 'tcp://proxy.example.com:8080';
$url = 'http://example.com/api/data';

$context = stream_context_create([
    'http' => [
        'proxy' => $proxy,
        'request_fulluri' => true, // Essential for HTTP proxies
    ],
]);

$response = @file_get_contents($url, false, $context);

if ($response === false) {
    echo 'Failed to retrieve content via proxy.';
} else {
    echo $response;
}
?>

request_fulluri must be set to true when using an HTTP proxy, as it instructs the client to send the full URI in the request line (e.g., GET http://example.com/path HTTP/1.0).

HTTPS Proxy

For HTTPS targets, the https stream wrapper handles the proxy setup similar to http.

<?php
$proxy = 'tcp://proxy.example.com:8080';
$url = 'https://secure.example.com/data';

$context = stream_context_create([
    'http' => [ // Note: Proxy configuration is still under 'http' for CONNECT tunneling
        'proxy' => $proxy,
        'request_fulluri' => true,
    ],
    'ssl' => [ // SSL/TLS verification options
        'verify_peer' => false, // Disable for testing, enable for production
        'verify_peer_name' => false,
    ],
]);

$response = @file_get_contents($url, false, $context);

if ($response === false) {
    echo 'Failed to retrieve content via proxy.';
} else {
    echo $response;
}
?>

Proxy with Authentication

Proxy authentication for file_get_contents is typically handled by manually setting the Proxy-Authorization header within the http context options.

<?php
$proxy = 'tcp://proxy.example.com:8080';
$url = 'http://example.com/api/data';
$proxyUser = 'proxyuser';
$proxyPass = 'proxypassword';

// Base64 encode the username:password for Basic authentication
$authHeader = 'Proxy-Authorization: Basic ' . base64_encode("$proxyUser:$proxyPass");

$context = stream_context_create([
    'http' => [
        'proxy' => $proxy,
        'request_fulluri' => true,
        'header' => $authHeader,
    ],
]);

$response = @file_get_contents($url, false, $context);

if ($response === false) {
    echo 'Failed to retrieve content via proxy.';
} else {
    echo $response;
}
?>

Limitations of file_get_contents with Proxies

  • No SOCKS Proxy Support: PHP's stream wrappers do not natively support SOCKS proxies.
  • Limited Error Handling: Error information is minimal, relying on warnings or false return values.
  • Less Control: Granular control over request headers, timeouts, and redirect handling is less flexible.
  • Performance: May be less performant for concurrent or numerous requests compared to cURL.

Comparison of PHP Proxy Methods

Feature cURL (via php-curl) Guzzle (via Composer) file_get_contents (via stream contexts)
Ease of Use Moderate (direct option setting) High (object-oriented, fluent interface) High (simple function call, context setup)
Proxy Types HTTP, HTTPS (CONNECT), SOCKS4/4a/5/5h HTTP, HTTPS (CONNECT), SOCKS4/5 HTTP, HTTPS (CONNECT)
Authentication CURLOPT_PROXYUSERPWD URI-embedded (user:pass@host) Manual Proxy-Authorization header
Error Handling Detailed (curl_errno, curl_error) Robust (exceptions, PSR-7 responses) Basic (false return, warnings)
Control Level High (granular control over all cURL options) High (wraps cURL, offers high-level options) Low (limited to stream context options)
SSL Verification CURLOPT_SSL_VERIFYPEER, CURLOPT_SSL_VERIFYHOST verify option ssl context options (verify_peer, verify_peer_name)
Redirect Handling CURLOPT_FOLLOWLOCATION, CURLOPT_MAXREDIRS allow_redirects option Limited (automatic for HTTP, less configurable)
Dependencies PHP cURL extension PHP cURL extension, Composer, Guzzle package None (built-in PHP function)
Best Use Case Complex, high-performance, low-level integration Modern applications, REST APIs, robust error handling Simple, quick scripts for basic GET requests
Auto-update: 03.03.2026
All Categories

Advantages of our proxies

25,000+ proxies from 120+ countries