Abidus Sattar
Abidus Sattar

Reputation: 13

file_put_contents to create file out of public directory in laravel

i am trying to create a file in laravels App/Http/Controller directory so i had used this code

$path = 'App/Http/Controller/';

    $fileName = 'demo.php';

    $contents = "<?php echo 'hello'; ?>";
   
   if (!file_exists($path)) {
        mkdir($path, 0755, true);
    }

    $path = $path.$fileName;

    file_put_contents($path, $contents);

but this is creating a file with directory in Public folder..

how to get rid of this.?

Upvotes: 1

Views: 3117

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4291

Setting up a Disk

You can setup a disk at config/filesystems.php and then benefit from Storage facade methods.

config/filesystems.php

'tmp' => [
    'driver' => 'local',
    'root'   => public_path('..'),
],

Notice: public_path() Starts from public folder, you can go one step ahead using public_path('..')

Using Storage Facade

You can now use Storage methods such as allDirectories and allFiles for retrieving directories and files, or put for saving new files as thoroughly explained in laravel doc.

Storage::disk('tmp')->allDirectories();
Storage::disk('tmp')->allFiles('routes');

// Storing new photo
Storage::disk('tmp')->put('newfile.jpg',$content);

Upvotes: 3

Related Questions