3

How to do HTTPS requests via proxy server

The proxy server is tinyproxy on debian

code

$context = stream_context_create([
    'http' => [
        'proxy' => 'tcp://xx.xx.xx.xx:8888',
        'request_fulluri' => true
    ]
]);

echo file_get_contents('https://www.google.com', false, $context);

error

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol in C:\wamp\www\google\test.php on line 10

Warning: file_get_contents(https://www.google.com): failed to open stream: Cannot connect to HTTPS server through proxy in C:\wamp\www\google\test.php on line 10
Community
  • 1
  • 1
clarkk
  • 27,151
  • 72
  • 200
  • 340

2 Answers2

2

The problem which causes your second warning can be fixed by changing 'http' in stream_context_create to 'https'

  • This only works because the options (and the proxy) are ignored. Special options for https can be added to the options with the key 'ssl', the key 'https' does nothing! – dieckie Sep 22 '22 at 19:12
1

I would recommend cURL to do this. Somewhere on stackoverflow a user said this and I totally agree.

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter. cURL with setopt is a powerdrills with almost every option you can think of.

<?php

$url = 'https://www.google.com';
// to check your proxy
// $url = 'http://whatismyipaddress.com/';
$proxy = '50.115.194.97:8080';

// create curl resource
$ch = curl_init();

// set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // read more about HTTPS http://stackoverflow.com/questions/31162706/how-to-scrape-a-ssl-or-https-url/31164409#31164409
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch); 

echo $output;

?>
PHPhil
  • 1,555
  • 13
  • 27
  • This worked for me, I was using `file_get_contents()` but the response was false, after trying this code it worked. Thanks @PHPhil – Christopher M. Jan 10 '17 at 15:51
  • 2
    That's an awful quote. [`file_get_contents` supports POST and other verbs, custom headers, time-outs, cookies and automatic redirect following](http://php.net/manual/en/context.http.php). This cURL fanboying needs to stop. – Quolonel Questions May 26 '17 at 08:23