start learning
Image 1
5368987565423210112

PHP Files and Directories

Working with Files and Directories in PHP involves various functions and techniques to create, read, write, and manipulate files and directories on a server's file system. PHP provides a rich set of functions for these operations, making it a powerful language for handling file and directory-related tasks.


File Handling

File Creation:

You can create a new file using the fopen() function and write data to it using fwrite().


$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "Hello, world!");
    fclose($file);
}

File Reading:

To read the contents of a file, you can use fread() or file_get_contents().


$content = file_get_contents("example.txt");
echo $content;

File Deletion:

To delete a file, you can use unlink().


unlink("example.txt");

Directory Handling

Directory Creation:

You can create a new directory using mkdir().


mkdir("new_directory");

Directory Listing:

To list the contents of a directory, you can use scandir().


$files = scandir("path/to/directory");
print_r($files);

Directory Deletion:

To remove a directory, it must be empty. You can use rmdir().


rmdir("empty_directory");

Recursively Delete Directory:

To delete a directory and its contents recursively, use a custom function like this:


function deleteDirectory($dir) {
    if (!is_dir($dir)) return;
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            $path = $dir . "/" . $file;
            if (is_dir($path)) {
                deleteDirectory($path);
            } else {
                unlink($path);
            }
        }
    }
    rmdir($dir);
}

deleteDirectory("directory_to_delete");

File and Directory Checks

File Existence Check:

To check if a file exists, you can use file_exists().


if (file_exists("example.txt")) {
    // File exists
}

Directory Existence Check:

To check if a directory exists, use is_dir().


if (is_dir("path/to/directory")) {
    // Directory exists
}

These are basic examples of working with files and directories in PHP. Keep in mind that you should always handle errors and exceptions appropriately, especially when dealing with file and directory operations, to ensure your code is robust and secure. Additionally, be cautious when deleting files and directories, as data loss can occur if not done carefully.


×