PHP file_get_contents在本地主机上不起作用

问题描述 投票:9回答:7

我正在从OSX上的MAMP服务器的localhost(http://172.16.65.1/)在我的网站上工作。我想从Google加载一些JSON,一些简单的测试显示我在这里遇到了问题。]

echo file_get_contents("http://www.google.com"); // FAILS
// PHP log: [07-Dec-2011 23:09:21] PHP Warning:  file_get_contents(http://www.google.com) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: Host is down in /Applications/MAMP/htdocs/-tests/get-json.php on line 3
echo file_get_contents("http://www.yahoo.com"); // FAILS

// echo file_get_contents("http://localhost"); // WORKS
// echo file_get_contents("http://172.16.65.1/"); // WORKS - My MAMP server

我该怎么办?在我的主机提供程序服务器上它可以正常工作。

php localhost echo file-get-contents
7个回答
6
投票

摘自file_get_contents的文档:

如果启用了fopen包装器,则可以将此功能用作URL的文件名。有关如何指定文件名的更多详细信息,请参见fopen()。请参阅受支持的协议和包装器,以获取有关各种包装器具有的功能,其使用说明以及它们可能提供的任何预定义变量的信息的链接。

检查file_get_contents,以便将php.ini设置为allow_url_fopen

编辑:

我没有注意到您实际上可以在本地使用allow_url_fopen,所以现在我认为这可能与您的on有关。

此外,如果尚未完成,请尝试在file_get_contents中设置firewall settings


11
投票

您还需要签入user_agent文件

php.ini

是否启用,如果不启用,则只需删除;标志

PHP.ini

3
投票

这可能是您的php.ini文件中的设置。有一个allow_url_fopen的设置,它可以启用/禁用从php打开远程文件的功能。出于安全原因,通常默认将其禁用。您可以通过添加以下行在php.ini中启用它:

extension = php_openssl.dll

同样,使用此功能时,请注意安全性。

allow_url_fopen = on


3
投票

尝试使用此功能代替file_get_contents():

allow_url_fopen = 1

它可以像file_get_contents()一样使用,但使用cURL。

在Ubuntu(或具有其他能力的其他类似Unix的操作系统)上安装cURL:

http://php.net/manual/en/filesystem.configuration.php

另请参阅<?php function curl_get_contents($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data; }


1
投票

在第二个中,您尝试在当前文件夹中打开一个名为localhost的文件,该文件不存在,因此会引发错误。请改用sudo apt-get install php5-curl sudo /etc/init.d/apache2 restart 。为了使它起作用,您必须设置allow_furl_open。


0
投票

我正在使用file_get_contents这样:file_get_contents(“ cURL”。$ screenname。“&count = 5”);

并且那没有用,所以我将https更改为http,然后它运行良好。

http://localhost

0
投票

对我来说,问题是https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=".$screenname."&count=5"); (解析为localhost的域)上不起作用,但在file_get_contents上起作用。也许它不喜欢自签名证书。我确实将https://domain.test.loc设置为ON,并且扩展名= php_openssl.dll。

© www.soinside.com 2019 - 2024. All rights reserved.