Skip to content
PHP Logo

What are the differences between using file_get_contents and stream_socket_client in PHP for retrieving data over a proxy with authentication?

When retrieving data over a proxy with authentication in PHP, using file_get_contents may not support proxy authentication directly. In this case, using stream_socket_client with stream_context_create allows you to set the necessary proxy authentication headers and credentials. This ensures that the request is properly authenticated and data can be retrieved successfully.

php
$proxy = 'proxy.example.com:8080';
$url = 'https://example.com/data';
$context = stream_context_create([
    'http' => [
        'proxy' => 'tcp://' . $proxy,
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic " . base64_encode("username:password") . "\r\n",
    ]
]);

$stream = stream_socket_client('tcp://' . $proxy, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
$data = file_get_contents($url, false, $context);

if ($data === false) {
    echo "Failed to retrieve data from URL.";
} else {
    echo $data;
}