Mohammad Aghayari
Mohammad Aghayari

Reputation: 1160

Error failed to open stream: No such file or directory in file_get_contents()

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

Upvotes: 0

Views: 5269

Answers (3)

ekaratas
ekaratas

Reputation: 92

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

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

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133380

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

Upvotes: 1

Kaivan Alimohammadi
Kaivan Alimohammadi

Reputation: 51

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

Upvotes: 0

Related Questions