Tutorial by Examples

Deleting files The unlink function deletes a single file and returns whether the operation was successful. $filename = '/path/to/file.txt'; if (file_exists($filename)) { $success = unlink($filename); if (!$success) { throw new Exception("Cannot delete $filename&qu...
Raw direct IO file_get_contents and file_put_contents provide the ability to read/write from/to a file to/from a PHP string in a single call. file_put_contents can also be used with the FILE_APPEND bitmask flag to append to, instead of truncate and overwrite, the file. It can be used along with LO...
Check if a path is a directory or a file The is_dir function returns whether the argument is a directory, while is_file returns whether the argument is a file. Use file_exists to check if it is either. $dir = "/this/is/a/directory"; $file = "/this/is/a/file.txt"; echo is_d...
If we need to parse a large file, e.g. a CSV more than 10 Mbytes containing millions of rows, some use file or file_get_contents functions and end up with hitting memory_limit setting with Allowed memory size of XXXXX bytes exhausted error. Consider the following source (top-1m.csv has exactly...
Opening a stream fopen opens a file stream handle, which can be used with various functions for reading, writing, seeking and other functions on top of it. This value is of resource type, and cannot be passed to other threads persisting its functionality. $f = fopen("errors.log", "a...
Copying files copy copies the source file in the first argument to the destination in the second argument. The resolved destination needs to be in a directory that is already created. if (copy('test.txt', 'dest.txt')) { echo 'File has been copied successfully'; } else { echo 'Failed to ...

Page 1 of 1