PHP function to check file existence by path
Write a PHP function that takes a file path as input and checks if the file exists.
Sample Solution:
PHP Code :
<?php
function checkFileExists($filePath) {
if (file_exists($filePath)) {
echo "File exists at path: " . $filePath;
} else {
echo "File does not exist at path: " . $filePath;
}
}
// Usage:
$filePath = "test.txt";
//$filePath = "i:/test.txt";
checkFileExists($filePath);
?>
Sample Output:
File does not exist at path: test.txt File exists at path: i:/test.txt
Explanation:
In the above exercise -
- Inside the function, we use the file_exists() function to check if the file exists at the given path. If the file exists, we display a message indicating its existence along with the file path. If the file does not exist, we display a message indicating that the file does not exist along with the file path.
- To use this function, you can provide the file path as an argument when calling the checkFileExists() function.
- When you run this program, it will output either "File exists at path: <file path>" or "File does not exist at path: <file path>", depending on whether the file exists or not.
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP program to read and display text file contents
Next: PHP script to count lines in a text file.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics