Using proxy with file_get_contents

2019-04-12 04:34发布

问题:

I am getting data for my application from a website, say x.com. I use the php function file_get_contents() to fetch the data. It is sure that , my server's ip address will be shown in x.com 's logs. Is there any way to hide my server's ip without using proxy?

If I have a proxy ,how to use it with file_get_contents() ?

I need to send the request in both HTTP POST and HTTP GET methods

回答1:

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);


回答2:

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!