欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP获取远道文件

程序员文章站 2022-05-24 09:33:29
...
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. 
PHP获取远道文件

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频