>  기사  >  백엔드 개발  >  PHP获取远道文件

PHP获取远道文件

WBOY
WBOY원래의
2016-06-13 13:24:03912검색

PHP获取远程文件
if(!($contents=file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=AMZN&e=.csv&f=slldltlclohgv'))){
die('fail to open yahoo');
};
echo $contents;


为什么平均要刷新3-4下才有一次成功,其他都会出现一个警告,提示 HTTP request failed!


------解决方案--------------------

C/C++ code
Bart Friederichs 16-Apr-2012 12:17
file_get_contents can do a POST, create a context for that first:

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);
                        
$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);
pperegrina 21-Dec-2011 11:30
For those having this problem when trying to get_file_contents(url):

Warning: file_get_contents(url): failed to open stream: HTTP request failed!  in xx on line yy

If you are behind a SonicWall firewall, read this:
https://bugs.php.net/bug.php?id=40197
(this little line: uncheck a box in the internal settings of the firewall labled "Enforce Host Tag Search with for CFS")

Apparently by default SonicWall blocks any HTTP request without a "Host:" header, which is the case in the PHP get_file_contents(url) implementation.

This is why, if you try to get the same URL from the same machine with cURL our wget, it works.

I hope this will be useful to someone, it took me hours to find out :)
godwraith01 at yahoo dot com 11-Oct-2011 04:16
I experienced a problem in using hostnames instead straight IP with some server destinations.

If i use file_get_contents("www.jbossServer.example/app1",...)
i will get an 'Invalid hostname' from the server i'm calling.

This is because file_get_contents probably will rewrite your request after getting the IP, obtaining the same thing as :
file_get_contents("xxx.yyy.www.zzz/app1",...)

And you know that many servers will deny you access if you go through IP addressing in the request.

With cURL this problem doesn't exists. It resolves the hostname leaving the request as you set it, so the server is not rude in response. <div class="clear">
                 
              
              
        
            </div>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.