5

I have some image files in public/image directory, so I want to determine if a file exist in that directory before I save a new file. How to determine if a file exist?

Laerte
  • 7,013
  • 3
  • 32
  • 50
Misterk
  • 633
  • 3
  • 9
  • 17

4 Answers4

11

file_exists(public_path($name)

here is my solution to check if file exists before downloading file.

if (file_exists(public_path($name)))
    return response()->download(public_path($name));
AmirRezaM75
  • 1,030
  • 14
  • 17
5

You can use the Storage Facade:

Storage::disk('image')->exists('file.jpg'); // bool

If you are using the disk image as shown above, you need to define a new disk in your config/filesystems.php and add the following entry in your disks array:

'image' => [
    'driver' => 'local',
    'root' => storage_path('app/public/image'),
    'visibility' => 'public',
],

Here is the documentation if you want to know more on that Facade: https://laravel.com/docs/5.2/filesystem

Hope it helps :)

Hammerbot
  • 15,696
  • 9
  • 61
  • 103
5

You could use Laravel's storage Facade as El_Matella suggested. However, you could also do this pretty easily with "vanilla" PHP, using PHP's built-in is_file() function :

if (is_file('/path/to/foo.txt')) {
    /* The path '/path/to/foo.txt' exists and is a file */
} else {
    /* The path '/path/to/foo.txt' does not exist or is not a file */
}
John Slegers
  • 45,213
  • 22
  • 199
  • 169
1

You can use this little utility to check if the directory is empty.

if($this->is_dir_empty(public_path() ."/image")){ 
   \Log::info("Is empty");
}else{
   \Log::info("It is not empty");
}

public function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
     if ($entry != "." && $entry != "..") {
     return FALSE;
     }
  }
  return TRUE;
}

source

Community
  • 1
  • 1
oseintow
  • 7,221
  • 3
  • 26
  • 31