Home > Back-end >  How to Check file exists in Laravel
How to Check file exists in Laravel

Time:10-06

I have a Laravel Controller Function file_fetch()

public function file_fetch(Request $request) {

        $file = request('routename');
        $destinationPath = public_path('/folder/'.$file);
        
        if(!File::exists($destinationPath)){
            $content = File::get($destinationPath);
            return view('filefetch', compact('file','content'));
        } 
        else {
            return redirect('/')->witherrormessage('NO such File Exists');
        }
    }

This works if i check for file public/folder/app/index.html and if i check for public/newfolder (newfolder doesnt exist) and hence it executes else function and redirects with error message, but if i search for public/folder/app/ I havent specified the file name, but the directory exists, hence the if(!File::exists($destinationPath)) function is getting executed!

i want to check just and files inside the directory and even if the directory exists, if file is not present, throw a error message, saying file doesnt exists.

CodePudding user response:

add one more additional condition to check given path is file but not a directory

public function file_fetch(Request $request) {

        $file = request('routename');
        $destinationPath = public_path('/folder/'.$file);
        
        if(!File::exists($destinationPath) && !is_dir($destinationPath)){
            $content = File::get($destinationPath);
            return view('filefetch', compact('file','content'));
        } 
        else {
            return redirect('/')->witherrormessage('NO such File Exists');
        }
    }

CodePudding user response:

You can probably fix your code by validating the routename input such that it will never be empty (and have a certain file extension maybe?) , which is nice to do anyhow.

If that fails, you can try File::isDirectory($dir) which basically calls is_dir(...).

Note that it might give you more control on your storage solution if you use the Storage::disk('public') functionalities from Laravel. The API is a bit different but there's a wide range of probabilities associated with it. Read more about that here: https://laravel.com/docs/8.x/filesystem#introduction.

  • Related