【问题标题】:file_get_contents with Lumen带流明的 file_get_contents
【发布时间】:2016-03-15 11:15:12
【问题描述】:

我把这段代码变成了一个函数(php 类):

$theFile = '/test/test.xml'; // these are in the public folder
dd(file_get_contents($theFile));

如果我转到mydomain.local/test/test.xml,我会得到有效的 xml 代码。

但是使用file_get_contents,我得到了这个错误:

file_get_contents(/test/test.xml): failed to open stream: No such file or directory

如何解决?

【问题讨论】:

  • file_get_contents() 相对于您的 php 脚本执行(并且您不会在正确执行实际代码的地方摆弄太多,因为 laravel 是如何工作的)如果您有该路径。使用base_path() . '/test/test.xml'
  • @Tezla 这不起作用
  • dang,你为什么不阅读docs,它在公共路径中你可以public_path('test/test.xml')。只是为了确定,dd 这段代码并查看路径 - 如果它是正确的,这就是你的答案。否则,祝你好运:) - 显然,我之前的评论不起作用,我假设测试目录与appconfig、...、vendor 一起位于根目录中。
  • 谢谢。突然有点希望了……我用的是 Lumen,public_path() 暂时没有在这个框架中实现(Lumen 5.1.6)

标签: php laravel file-get-contents lumen


【解决方案1】:

Lumen 没有您在 Laravel 中可能熟悉的 public_path() 来轻松获取公共文件的路径。

重新实现它的最简单方法是在您的项目中添加一个名为 irazasyed/larasupport 的包,它会添加各种缺少的帮助程序(包括 public_path())以及添加 Lumen 中缺少的供应商发布命令。

或者,如果您不想添加第三方包,只需在您的应用程序目录中创建一个名为 helpers.php 的文件,然后在您的 composer.json 文件中的“自动加载”部分中添加以下内容并运行 composer dump-autoload 到刷新自动加载器缓存:

"files": [
    "app/helpers.php"
],

然后在helpers.php内添加如下内容:

<?php
if (!function_exists('public_path')) {
   /**
    * Get the path to the public folder.
    *
    * @param  string $path
    * @return string
    */
    function public_path($path = '')
    {
        return env('PUBLIC_PATH', base_path('public')) . ($path ? '/' . $path : $path);
    }
}

【讨论】:

  • 优秀的答案!我选择了我认为更安全的irazasyed 解决方案
  • @Zl3n 你怎么知道它更安全?它可能使用相同的东西。我想它的作用几乎相同here
  • 不应该将自动加载字符串更改为“helpers.php”,因为composer.json驻留在应用程序中,因此删除应用程序?
【解决方案2】:

您传递的是相对于服务器基目录的函数的绝对路径。这不需要与 URL 相同的基本目录。尝试传递相对于当前执行脚本的路径。

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2018-09-17
    • 2015-03-31
    相关资源
    最近更新 更多