What are some best practices for handling file and directory existence checks in PHP?
When working with files and directories in PHP, it's important to check if they exist before attempting any operations on them to avoid errors. One common practice is to use the `file_exists()` function to check if a file or directory exists before proceeding with any actions.
// Check if a file exists
$file_path = 'path/to/file.txt';
if (file_exists($file_path)) {
// File exists, proceed with operations
echo 'File exists!';
} else {
// File does not exist
echo 'File does not exist.';
}
// Check if a directory exists
$dir_path = 'path/to/directory';
if (is_dir($dir_path)) {
// Directory exists, proceed with operations
echo 'Directory exists!';
} else {
// Directory does not exist
echo 'Directory does not exist.';
}