【发布时间】:2016-02-03 10:05:54
【问题描述】:
我写了一个小脚本来测试我的项目中的一个功能,它工作得很好。
<?php
$username = 'exportcsv';
$password = 'exportcsv';
$context = \stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . \base64_encode("$username:$password"),
'timeout' => 2
)
));
$content = \file_get_contents('http://theurl', false, $context);
var_dump($content);
url 实际上是一个硬编码的 Symfony 路由,它返回一个 CSV 文本字符串。
但是当我在控制器上做同样的事情时,我得到:
Warning: file_get_contents(http://myurl): failed to open stream: HTTP request failed! (http://myurl): failed to open stream: HTTP request failed!
无论我使用file() 还是file_get_contents(),都会生成相同的硬编码网址或绝对路径:
$url = $this->generateUrl('the_route_name', array(
'variable' => $variable
), true);
编辑:也许这是一件重要的事情要注意,我在公司代理后面,所以我在上下文数组中添加 'proxy' => 'http://proxy.mycompany.com:3128' 现在我得到了:failed to open stream: Unable to find the socket transport &quot;http&quot; - did you forget to enable it when you configured PHP?
无论有无'request_fulluri' => true, 或'request_fulluri' => false,,都一样
【问题讨论】:
-
您是否尝试在
file_get_contents方法之前删除\? -
是的,当然,它或多或少都没有做任何事情(我很惊讶,因为我在想如果我们在一个特定的命名空间中,我们需要用我们想要使用的 \ 来指定在 \ 之后指定 PHP 标准库函数。例如,当我使用不带 \ 的 ZipArchive 类时,出现上下文错误。
-
@Vardius 你觉得代理怎么样?我在上下文数组 'proxy' => 'proxy.mycompany.com:3128' 中添加,现在我得到:未能打开流:无法找到套接字传输“http” - 你是不是在配置PHP的时候忘记开启了?
-
\ 用于包含命名空间和类,而不是用于使用全局 php 函数
-
关于代理请遵循这个答案,它应该可以帮助你stackoverflow.com/a/1336419/2160958
$aContext = array( 'http' => array( 'proxy' => 'tcp://192.168.0.2:3128', 'request_fulluri' => true, 'header' => "Proxy-Authorization: Basic $auth", ), ); $cxContext = stream_context_create($aContext);
标签: php symfony file-get-contents