2016-08-14 107 views
0

我试图通过使用file_get_contents()函数显示文本文件的内容(1.txt),当然我正在使用yii2框架。错误未能打开流:file_get_contents()中没有这样的文件或目录()

如果在yii2中有更简单的功能,请给我建议。

这是我在控制器代码:

public function actionRandom() { 

     $fileContent = file_get_contents(Yii::$app->request->baseUrl.'/files/upload/1.txt',true); 
     echo Json::encode($fileContent); 
     Yii::app()->end(); 

     return $this->render('random', [ 
         ] 
     ); 
    } 

我在结果得到这个错误。

file_get_contents(/test/files/upload/1.txt): failed to open stream: No such file or directory 

该文件存在于路径中,但我不知道为什么会出现此错误。

这些答案对我没有帮助。

first

second

+0

添加http://到开始的file_get_contents部分。 – Farkie

+0

可能重复的[无法打开流:没有这样的文件或目录](http://stackoverflow.com/questions/36577020/failed-to-open-stream-no-such-file-or-directory) –

回答

0

如果u确保文件的URL或路径是正确的,所以检查文件权限。

+0

怎么办我必须这样做? –

+0

sudo chmod 775文件名 –

+0

我听不懂。请详细解释。 –

1

尝试使用绝对URL

use yii\helpers\Url 

Url::to(Yii::$app->request->baseUrl .'/files/upload/1.txt' , true); 
$fileContent = file_get_contents(Url::to(Yii::$app->request->baseUrl 
     .'/files/upload/1.txt' , true),true); 
+0

我想在变量中包含文件的内容。没有链接到那个。 –

+0

答案为file_get_contents()提供了正确的链接,然后file_get:内容应该返回$ fileContent中的文件内容 – scaisEdge

0
​​

会工作,如果你的文件存在 '/yourproject/web/files/upload/1.txt'