Working With Files In PHP
Here are some basic functions we can use when working with files in PHP.
I. List all files and directories
We can use the function scandir() to list all files and directories of a specific path.
Syntax
scandir(directory, order)
order:
We can specify the sorting order. The default sort order is ascending order (0).
- SCANDIR_SORT_DESCENDING or 1 to sort in alphabetical descending order.
- SCANDIR_SORT_NONE to return the result unsorted.
Example
$dir = scandir(__DIR__);
var_dump($dir);
// array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(9) ".DS_Store" [3]=> string(9) "index.php" }
II. Check if it’s a file or directory
We can check whether a specific filename is a file or a directory using is_file() or is_dir().
Syntax
// Check if it's a file
is_file(file)
// Check if it's a directory
is_dir(file)
Example
$dir = scandir(__DIR__);
var_dump(is_file($dir[2])); // bool(true)
var_dump(is_dir($dir[2])); // bool(false)
III. Check if file or directory exists
We can check if a file or a directory exists using the file_exists() function. This function’s result is cached.
Syntax
file_exists(path)
Example
if (file_exists("text.txt")) {
echo filesize("text.txt");
} else {
echo "File not found";
} // File not found
IV. Clear cache
PHP cache the return value of some file-related functions for better performance.
Affected functions: stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
We can use clearstatcache() to clear the cache.
Syntax
clearstatcache()
V. Create a directory
We can create a new directory using the mkdir() function.
Syntax
mkdir(path);
Example
mkdir("partials");
VI. Delete a directory
We can delete a directory using the rmdir() function.
Syntax
rmdir(dir)
Example
rmdir("partials");
VII. Open file
We can open a file using the fopen() function.
Syntax
fopen(filename, mode)
There are several modes for fopen .
- “r”: Read only.
- “r+”: Read/Write.
- “w”: Write only. Opens file or creates a new file if it doesn’t exist.
Example
$file = fopen("text.txt", "r");
VIII. Close a file
Syntax
We use the fclose() function to close an open file.
fclose(file)
Example
$file = fopen("text.txt", "r");
fclose($file);
IX. feof()
We can check if the “end-of-file” is reached for an open file usingfeof().
It’s useful in loops.
X. Read file line by line
We can use the fgets() function to return a line from an open file.
Syntax
fgets(file)
Example
$file = fopen("text.txt","r");
while(! feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
XI. Read CSV files
The fgetcsv() function parses a line from an open file and returns an array.
Syntax
fgetcsv(file, length, separator)
Example
$file = fopen("text.txt","r");
while(! feof($file)) {
echo "<pre>";
print_r(fgetcsv($file));
echo "</pre>";
}
fclose($file);
/* Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => d
[1] => e
[2] => f
)
Array
(
[0] => g
[1] => h
[2] => i
) */
XII. Get file content
We can read file content using the file_get_contents() function.
Syntax
file_get_contents(path, include_path, start, max_length)
Example
echo file_get_contents("text.txt", offset: 2, length: 3);
// llo
XIII. Write content to a file
We can write content to a file using the file_put_contents() function.
Syntax
file_put_contents(filename, data, mode, )
Example
echo file_put_contents("text.txt","Testing!");
XIV. Delete, copy, rename files
- To delete a file, we use the function
unlink(). - To copy a file, we use the function
copy(). If the to_fine file already exists, it will be overwritten. - To rename a file, we use the function
rename().
Syntax
unlink(filename)
copy(from_file, to_file)
rename(old, new)
Example
unlink("text.txt");
echo copy("from.txt","to.txt");
rename("/partials/file1.txt","/docs/file2.txt");
XV. Check path info
We can check information about a file path using the pathinfo() function.
Syntax
pathinfo(path, options)
Option values
- PATHINFO_DIRNAME: return only dirname.
- PATHINFO_BASENAME: return only basename.
- PATHINFO_EXTENSION: return only extension.
- PATHINFO_FILENAME: return only filename.
Example
print_r(pathinfo("/docs/text.txt"));