Skip to content
PHP Logo

How can conditional statements be used to improve file handling functionality in PHP scripts?

Conditional statements can be used in PHP scripts to improve file handling functionality by checking for specific conditions before performing file operations. For example, you can use conditional statements to check if a file exists before attempting to read from or write to it, or to determine whether a file is writable before attempting to modify it. This can help prevent errors and handle different scenarios more effectively.

php
// Check if a file exists before reading from it
$file = 'example.txt';
if (file_exists($file)) {
    $content = file_get_contents($file);
    echo $content;
} else {
    echo 'File does not exist.';
}

// Check if a file is writable before modifying it
$file = 'example.txt';
if (is_writable($file)) {
    file_put_contents($file, 'New content');
    echo 'File updated successfully.';
} else {
    echo 'File is not writable.';
}