【问题标题】:In PHP file_get_contents works in command line but not in my Symfony project在 PHP 中 file_get_contents 在命令行中有效,但在我的 Symfony 项目中无效
【发布时间】: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' =&gt; 'http://proxy.mycompany.com:3128' 现在我得到了:failed to open stream: Unable to find the socket transport &amp;quot;http&amp;quot; - did you forget to enable it when you configured PHP?

无论有无'request_fulluri' =&gt; true,'request_fulluri' =&gt; false,,都一样

【问题讨论】:

  • 您是否尝试在file_get_contents方法之前删除\?
  • 是的,当然,它或多或少都没有做任何事情(我很惊讶,因为我在想如果我们在一个特定的命名空间中,我们需要用我们想要使用的 \ 来指定在 \ 之后指定 PHP 标准库函数。例如,当我使用不带 \ 的 ZipArchive 类时,出现上下文错误。
  • @Vardius 你觉得代理怎么样?我在上下文数组 'proxy' => 'proxy.mycompany.com:3128' 中添加,现在我得到:未能打开流:无法找到套接字传输“http” - 你是不是在配置PHP的时候忘记开启了?
  • \ 用于包含命名空间和类,而不是用于使用全局 php 函数
  • 关于代理请遵循这个答案,它应该可以帮助你stackoverflow.com/a/1336419/2160958$aContext = array( 'http' =&gt; array( 'proxy' =&gt; 'tcp://192.168.0.2:3128', 'request_fulluri' =&gt; true, 'header' =&gt; "Proxy-Authorization: Basic $auth", ), ); $cxContext = stream_context_create($aContext);

标签: php symfony file-get-contents


【解决方案1】:

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

所以当file_get_contents 的上下文无法获取数据时。使用我的 Apache2 Web 服务器时,一切正常。

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

这并没有告诉我为什么它在命令行和单个脚本中工作。

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2021-10-11
    • 2013-10-14
    • 1970-01-01
    • 2021-11-01
    • 2017-08-17
    • 2021-11-13
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多