Skip to content
PHP Logo

What are some best practices for handling proxy servers in PHP when making external requests?

When making external requests in PHP, it may be necessary to route the requests through a proxy server for various reasons such as security or accessing restricted resources. To handle proxy servers in PHP, you can use the `stream_context_set_default` function to set the proxy configuration before making the external request.

php
$proxy = 'tcp://proxy.example.com:3128';
$proxy_auth = 'username:password';

$context = stream_context_create([
    'http' => [
        'proxy' => $proxy,
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic " . base64_encode($proxy_auth)
    ]
]);

stream_context_set_default($context);

$response = file_get_contents('https://www.example.com');