4

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
  • 6,773
  • 3
  • 31
  • 49
Misterk
  • 613
  • 3
  • 9
  • 16

4 Answers4

10

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
  • 810
  • 10
  • 13
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
  • 14,352
  • 7
  • 53
  • 95
4

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
  • 41,615
  • 22
  • 193
  • 161
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
  • 6,761
  • 3
  • 24
  • 29