w3resource

PHP File: Check if a file is writable or not

PHP File Handling: Exercise-10 with Solution

Write a PHP program that checks if a file is writable and displays appropriate messages.

Sample Solution:

PHP Code :

<?php
$filename = "i:/test.txt";

try {
    if (is_writable($filename)) {
        echo "The file is writable.";
    } else {
        echo "The file is not writable.";
    }
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}

?>

Sample Output:

The file is writable.

Explanation:

In the above exercise -

  • The $filename variable holds the name of the file you want to check.
  • Inside the try block, we use the is_writable() function to check if the file is writable. If it is writable, we display the message "The file is writable." If it is not writable, we display the message "The file is not writable."
  • If an error occurs during the check, the catch block will catch the exception and display an error message using $e-<getMessage().

Flowchart:

Flowchart: Check if a file is writable or not

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: PHP function to check file size in human-readable format.
Next: Program to add a string to an existing file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.