Using proxy with file_get_contents

浪尽此生 提交于 2019-12-03 16:36:58

test.php using http://ifconfig.me/ip

code modified from http://www.php.net/manual/en/function.file-get-contents.php

<?php

// Create a stream
$opts = array(
        'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n",
            'proxy' => 'tcp://221.176.14.72:80',
            )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://ifconfig.me/ip', false, $context);

var_dump($file);

Definitely agree with farmer1992.

For anyone having issues with file_get_contents over SSL + proxy, there is a known bug with PHP's stream_context_create:

https://bugs.php.net/bug.php?id=63519

Fortunately, the workaround is simple. Basically, the context creator gets confused when parsing an "https" target URL to both the proxy and SSL configs. You just have to set the SNI_server_name in the SSL config:

$targetUrl = "https://something.com";
$sniServer = parse_url($targetUrl, PHP_URL_HOST);
$params = array('your'=>'post','params'=>'here');
$ctxConfig = array(
    'http' => array(
        'method' => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded'."\r\n",
        'content' => http_build_query($params),
        'proxy' => 'tcp://12.34.56.78:3128',
        'request_fulluri' => true
    ),
    'ssl' => array( 
        'SNI_enabled' => true,
        'SNI_server_name' => $sniServer
    )
);
$context = stream_context_create($ctxConfig);
file_get_contents($targetUrl,false,$context)

Hopefully that saves someone some time!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!