在PHP中,file_get_contents可以在命令行中工作,但不能在我的Symfony项目中工作


In PHP file_get_contents works in command line but not in my Symfony project

我写了一个小脚本来测试我的项目上的功能,它工作得很好。

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

该网址实际上是一个硬编码的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 或生成的绝对路径:

$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,

我找到了解决方案。我通过symfony命令使用PHP内置服务器:app/console server:run (bin/console server:run since 2.8+)

因此,当file_get_contents的上下文无法获取 de 数据时。使用我的 Apache2 网络服务器时,一切正常。

我搜索但找不到如何在上下文的 http 数组中设置端口值。

这并不能告诉我为什么它适用于命令行和单个脚本。

相关文章: