0

I'm trying to show content of text file (1.txt) by using file_get_contents() function, and of course I'm working with yii2 framework.

if there is simpler function in yii2 please suggest me.

Here is my code in controller:

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', [
                        ]
        );
    }

I get this error in result.

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

The file is exist in the path, but I don't know why I get this error.

These answers didn't help me well.

first

second

Community
  • 1
  • 1
Mohammad Aghayari
  • 1,010
  • 3
  • 15
  • 38

3 Answers3

1

Try using an absolute 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);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

if u sure file Url or path is correct, so check file permissions.

0
file_get_contents(dirname(__DIR__).'/../web/files/upload/1.txt',true);

will works if your file exists '/yourproject/web/files/upload/1.txt'

ekaratas
  • 92
  • 5