PHP is a versatile scripting language widely used in web development, and it provides a rich set of functions for working with files and directories. In this blog post, we’ll explore some of these functions in PHP 8, along with practical examples and expected outputs.
1. __FILE_
In PHP, you can use the __FILE__
magic constant to obtain the current file’s absolute path. This constant provides the full path to the script that it’s used in. Here’s an example of how to use it:
<?php
$file_path = __FILE__;
echo "The path of current file is: " ."<br>". $file_path;
?>
When you run this code in a PHP script, it will output something like:

2. pathinfo
The pathinfo
function allows you to extract information about a file path. It returns an associative array containing details like the directory name, base name, extension, and filename.
<?php
$path = __FILE__;
$pathInfo = pathinfo($path);
echo "<pre>";
print_r($pathInfo);
echo "</pre>";
?>
Output:

3. unlink
unlink
is used to delete a file.
<?php
$fileToDelete = "file_old.txt";
if (unlink($fileToDelete)) {
echo "File deleted successfully.";
} else {
echo "Unable to delete the file.";
}
?>
Output (if the file exists and is deleted):

4. copy
copy
is used to copy a file from one location to another.
<?php
$sourceFile = "index.php";
$destinationFile = "about.php";
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully.";
} else {
echo "Unable to copy the file.";
}
?>
Output (if the copy is successful):

5. rename
rename
is used to rename a file or directory.
<?php
$oldName = "about.php";
$newName = "contact.php";
if (rename($oldName, $newName)) {
echo "File renamed successfully.";
} else {
echo "Unable to rename the file.";
}
?>
Output (if the rename is successful):

6. scandir
scandir
lists files and directories in a directory.
<?php
$directory = __DIR__;
$files = scandir($directory);
echo "<pre>";
print_r($files);
echo "</pre>";
?>
Output

7. is_dir / is_file
These functions check if a path is a directory or a file.
<?php
$path = __DIR__;
$path_file = __FILE__;
if (is_dir($path)) {
echo "It's a directory.";
} elseif (is_file($path)) {
echo "It's a file.";
} else {
echo "It's neither a directory nor a file.";
}
?>
Output (based on the type of path):
