Working with FILES in PHP - heikijapan/php-book2 GitHub Wiki

These are some useful functions to work with files:

opendir()

  • this opens a FILE STREAM of a DIR. And is recommended to used with closedir() to close the stream and open resources. But PHP is very smart and it will close the stream and clean up automatically, but for clean code purposes try to use opendir() and closedir as a pair.

  • it is usually used with $handle variable which is the OPEN STREAM that this function creates, like this $handle = opendir(__DIR__ . '/images');

closedir()

  • this is an opposite to opendir() function which closes FILE STREAM. It should be used with opendir() function.

readdir()

  • this is a very helpful function which reads files inside a DIR one by one and remembers the last file it went through. Usually used together with WHILE loop.

scandir()

  • it scans the directory and gives back files as an array

pathinfo()

  • This is very cool function which does not communicate with file system but gives back info about the file in an array form. BUT it does not care if the path or file actually EXIST!!! It just reads the file as a string and interprets what it can from that given string (not a real file).
var_dump(pathinfo('my_lovely_file.pdf'));

// above pathinfo() function gives back this info about the file string
array(4) {
  ["dirname"]=>
  string(1) "."
  ["basename"]=>
  string(18) "my_lovely_file.pdf"
  ["extension"]=>
  string(3) "pdf"
  ["filename"]=>
  string(14) "my_lovely_file"
}
// It can also extract only info needed eg filename or extension. For that PATHINFO_EXTENSION constants are used.
// BUT it does not care if that extension really exists or not, it will just take the last thing which is separated by '.' dot and that's it.

echo pathinfo('my_lovely_file.pdf', PATHINFO_EXTENSION); // output will be 'pdf'.

filesize()

  • gives file size in bytes and if you want to make it to KB then filesize($my_file) / 1024 and when MB needed then filesize($my_file) / 1024 / 1024

is_dir()

  • checks if the directory exists

is_file()

  • this function is much more precise than is_dir because it checks both is bath and the file exist and if bath does not exist then it already fails (false).

is_readable()

  • checks permissions if PHP can read the file

is_writable()

  • can PHP write on this file or not? it checks permissions.

file_exists()

  • it checks if a path on filesystem exists

  • path can point to a file or folder (dir)

  • it does not tell if it is a dir or a file

  • if expecting a file then is_file() and if expecting a dir then is_dir should be used

  • this checks if a folder or file exists, but it does not check if it is a true file because filesystems can also have just links and shortcuts as well. Therefore more specific functions like is_file and is_dir should be used.