Bird
Raised Fist0
PHPprogramming~15 mins

File existence and info checks in PHP - Deep Dive

Choose your learning style10 modes available
Overview - File existence and info checks
What is it?
File existence and info checks in PHP are ways to find out if a file or directory exists and to get details about it. This includes checking if a file is readable, writable, or what type it is. These checks help your program decide what to do next safely. Without them, your code might try to use files that aren't there or can't be accessed.
Why it matters
These checks prevent errors and crashes when your program works with files. Imagine trying to open a missing file or write to a locked one — your program would fail. By checking first, you avoid these problems and make your code more reliable and user-friendly.
Where it fits
Before learning this, you should know basic PHP syntax and how to work with files simply. After this, you can learn about file handling functions like reading, writing, and deleting files safely.
Mental Model
Core Idea
Before using a file, always ask PHP if it exists and what you can do with it to avoid surprises.
Think of it like...
It's like checking if a door is locked or open before trying to enter a room. You don't want to bang on a locked door or walk into a wall.
┌───────────────┐
│ File Path     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check Exists? │──No──> Stop or Create
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Check Readable│──No──> Warn or Skip
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Check Writable│──No──> Warn or Read-Only
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Use File      │
└───────────────┘
Build-Up - 7 Steps
1
FoundationCheck if a file exists
🤔
Concept: Learn how to use PHP's file_exists() function to see if a file or directory is present.
Result
If 'example.txt' is in the folder, it prints 'File exists.' Otherwise, 'File does not exist.'
Knowing if a file exists before using it prevents errors like trying to open something that isn't there.
2
FoundationCheck if a file is readable
🤔
Concept: Use is_readable() to find out if PHP can read the file's contents.
Result
Prints 'File is readable.' if PHP has permission to read the file, else 'File is not readable.'
Even if a file exists, it might not be readable, so checking avoids permission errors.
3
IntermediateCheck if a file is writable
🤔Before reading on: do you think a file that exists is always writable? Commit to your answer.
Concept: Use is_writable() to check if PHP can write or change the file.
Result
Prints 'File is writable.' if PHP can write to the file, else 'File is not writable.'
Understanding write permissions helps avoid errors when saving or modifying files.
4
IntermediateCheck if path is a directory
🤔Before reading on: do you think file_exists() returns true for directories? Commit to your answer.
Concept: Use is_dir() to check if a path is a folder instead of a file.
Result
Prints 'This is a directory.' if 'myfolder' is a folder, else 'This is not a directory.'
Knowing if a path is a folder or file helps your program handle them correctly.
5
IntermediateGet file size and type info
🤔
Concept: Use filesize() and filetype() to learn about the file's size and what kind it is.
Result
Prints the file size in bytes and the type like 'file' or 'dir'.
Getting file details helps decide how to process or display files.
6
AdvancedCombine checks for safe file use
🤔Before reading on: do you think checking only file_exists() is enough for safe file handling? Commit to your answer.
Concept: Combine multiple checks to ensure the file exists, is readable, and writable before using it.
Result
Prints 'File is ready for use.' only if all conditions are true, else 'File is not ready.'
Combining checks prevents many common file handling errors in real applications.
7
ExpertBeware of race conditions in file checks
🤔Before reading on: do you think file existence checks guarantee the file stays the same after checking? Commit to your answer.
Concept: Understand that between checking a file and using it, the file might change or disappear, causing errors.
PHP code often checks file_exists() before opening a file. But if another process deletes or changes the file right after the check, your program can fail. To avoid this, open the file directly and handle errors, or use locking mechanisms.
Result
Knowing this prevents bugs where files vanish or permissions change between checks and use.
Understanding race conditions helps write safer, more robust file handling code in multi-user or multi-process environments.
Under the Hood
PHP's file existence and info functions ask the operating system about the file system. When you call file_exists(), PHP sends a request to the OS to check if the file path is valid. Similarly, is_readable() and is_writable() check the file's permissions by querying the OS. These functions do not open the file but rely on metadata stored by the file system. This means they are fast but can be outdated if the file changes immediately after the check.
Why designed this way?
These functions were designed to provide quick, simple checks without opening files, which can be expensive or risky. By separating existence and permission checks from actual file operations, PHP lets programmers write safer code. However, this design trades off atomicity, meaning the file state can change between checks and use, which is a known limitation in many systems.
┌───────────────┐
│ PHP Function  │
│ (e.g., file_exists)
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ OS File System│
│ Metadata Info │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ File Metadata │
│ (Exists, Perms)
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does file_exists() return true for directories? Commit yes or no.
Common Belief:file_exists() only returns true for files, not directories.
Tap to reveal reality
Reality:file_exists() returns true for both files and directories if the path exists.
Why it matters:Mistaking this causes wrong assumptions about what paths exist, leading to bugs when handling directories.
Quick: If file_exists() returns true, is the file always readable? Commit yes or no.
Common Belief:If a file exists, PHP can always read it.
Tap to reveal reality
Reality:A file can exist but still be unreadable due to permissions or locks.
Why it matters:Assuming readability causes errors when trying to open or read files without permission.
Quick: Does checking file_exists() guarantee the file won't change before use? Commit yes or no.
Common Belief:Once file_exists() returns true, the file is safe to use without errors.
Tap to reveal reality
Reality:The file can be deleted or changed after the check, causing errors later.
Why it matters:Ignoring this leads to race condition bugs that are hard to find and fix.
Quick: Does is_writable() check if the file is writable by the current PHP script? Commit yes or no.
Common Belief:is_writable() always accurately reflects if PHP can write to the file.
Tap to reveal reality
Reality:is_writable() checks permissions but external factors like locks or disk space can still prevent writing.
Why it matters:Relying solely on is_writable() can cause unexpected write failures.
Expert Zone
1
File existence checks are fast but not atomic; always handle errors when opening files to avoid race conditions.
2
Permissions can differ between the PHP process user and the file owner, so checks might not reflect actual access rights.
3
Network file systems or symbolic links can cause unexpected results in existence and permission checks.
When NOT to use
Avoid relying only on file existence checks in multi-user or multi-process environments where files can change quickly. Instead, use file locking functions like flock() or open files with error handling to ensure safe access.
Production Patterns
In real-world PHP applications, developers combine existence and permission checks with try-catch blocks or error handling when opening files. They also use file locks to prevent simultaneous writes and validate file paths to avoid security risks like path traversal.
Connections
Operating System File Permissions
Builds-on
Understanding OS-level permissions helps explain why PHP's is_readable() and is_writable() behave the way they do.
Race Conditions in Concurrent Programming
Same pattern
File existence checks illustrate race conditions where state changes between check and use, a core concept in concurrent programming.
Locking Mechanisms in Database Systems
Similar solution
Just like databases use locks to prevent conflicts, file locking prevents race conditions in file access.
Common Pitfalls
#1Assuming file_exists() means the file is ready to use without further checks.
Wrong approach:
Correct approach:
Root cause:Believing existence alone guarantees safe reading ignores permission issues.
#2Checking file_exists() then opening the file without handling errors.
Wrong approach:
Correct approach:
Root cause:Ignoring that the file can change after the check leads to unhandled errors.
#3Using is_writable() to decide if you can write without checking disk space or locks.
Wrong approach:
Correct approach:
Root cause:Assuming permissions are the only factor for writing ignores other failure causes.
Key Takeaways
Always check if a file exists before trying to use it to avoid errors.
File existence does not guarantee readability or writability; always check permissions.
File state can change between checks and use, so handle errors when opening or writing files.
Use combined checks and error handling for safe and reliable file operations.
Understanding underlying OS permissions and race conditions helps write robust file handling code.

Practice

(1/5)
1. Which PHP function checks if a file or directory exists at a given path?
easy
A. filesize()
B. is_file()
C. file_exists()
D. is_readable()

Solution

  1. Step 1: Understand the purpose of file_exists()

    The function file_exists() returns true if the file or directory exists at the specified path.
  2. Step 2: Compare with other functions

    Functions like is_file() check if the path is a file, filesize() returns size, and is_readable() checks permissions, but none check existence alone.
  3. Final Answer:

    file_exists() -> Option C
  4. Quick Check:

    Check existence = file_exists() [OK]
Hint: Use file_exists() to check any file or directory presence [OK]
Common Mistakes:
  • Confusing is_file() with existence check
  • Using filesize() to check existence
  • Assuming is_readable() means file exists
2. Which of the following is the correct syntax to check if a path is a directory in PHP?
easy
A. is_directory($path);
B. is_dir($path);
C. file_is_dir($path);
D. dir_exists($path);

Solution

  1. Step 1: Recall the correct function name

    PHP uses is_dir() to check if a path is a directory.
  2. Step 2: Verify syntax correctness

    The function is called as is_dir($path); other options are invalid function names.
  3. Final Answer:

    is_dir($path); -> Option B
  4. Quick Check:

    Directory check = is_dir() [OK]
Hint: Remember: is_dir() checks directories, not is_directory() [OK]
Common Mistakes:
  • Using non-existent functions like is_directory()
  • Mixing up is_file() and is_dir()
  • Missing parentheses in function call
3. What will the following PHP code output if the file 'example.txt' exists and is 150 bytes in size?
$file = 'example.txt';
if (file_exists($file)) {
    echo filesize($file);
} else {
    echo 'File not found';
}
medium
A. 150
B. Error
C. 0
D. File not found

Solution

  1. Step 1: Check file existence

    The code uses file_exists() to confirm 'example.txt' exists, which it does.
  2. Step 2: Output file size

    Since the file exists, filesize($file) returns 150, which is printed.
  3. Final Answer:

    150 -> Option A
  4. Quick Check:

    File exists, output size = 150 [OK]
Hint: filesize() returns size only if file_exists() is true [OK]
Common Mistakes:
  • Assuming filesize() works without checking existence
  • Confusing filesize() output with file content
  • Expecting 'File not found' when file exists
4. Identify the error in this PHP code snippet that checks if a file is writable:
$filename = 'data.txt';
if (is_writeable($filename)) {
    echo 'Writable';
} else {
    echo 'Not writable';
}
medium
A. Missing semicolon after echo statements
B. is_writeable() does not check permissions
C. $filename should be in double quotes
D. The function name is misspelled; should be is_writable()

Solution

  1. Step 1: Check function spelling

    The correct function to check if a file is writable is is_writable(), not is_writeable().
  2. Step 2: Verify other syntax

    Semicolons are present, variable quotes are valid, and is_writable() does check permissions.
  3. Final Answer:

    The function name is misspelled; should be is_writable() -> Option D
  4. Quick Check:

    Correct spelling = is_writable() [OK]
Hint: Remember: writable has one 'e' after writ [OK]
Common Mistakes:
  • Misspelling is_writable() as is_writeable()
  • Thinking variable needs double quotes
  • Confusing permission check with existence
5. You want to list all files in a directory 'docs/' that exist, are readable, and have been modified in the last 24 hours. Which PHP code snippet correctly implements this?
hard
A. $files = scandir('docs/'); foreach ($files as $file) { $path = 'docs/' . $file; if (file_exists($path) && is_readable($path) && (time() - filemtime($path) < 86400)) { echo $file . "\n"; } }
B. $files = scandir('docs/'); foreach ($files as $file) { if (is_dir($file)) continue; if (is_writable($file)) { echo $file . "\n"; } }
C. $files = scandir('docs/'); foreach ($files as $file) { if (file_exists($file) && filesize($file) > 0) { echo $file . "\n"; } }
D. $files = scandir('docs/'); foreach ($files as $file) { if (is_file($file) && is_readable($file)) { echo $file . "\n"; } }

Solution

  1. Step 1: Understand requirements

    We need to list files in 'docs/' that exist, are readable, and modified within last 24 hours (86400 seconds).
  2. Step 2: Analyze each option

    $files = scandir('docs/'); foreach ($files as $file) { $path = 'docs/' . $file; if (file_exists($path) && is_readable($path) && (time() - filemtime($path) < 86400)) { echo $file . "\n"; } } correctly scans 'docs/', builds full path, checks file_exists(), is_readable(), and filemtime() against current time minus 86400 seconds. Other options miss one or more conditions or use wrong paths.
  3. Final Answer:

    Option A code snippet -> Option A
  4. Quick Check:

    Check existence + readability + recent mod = $files = scandir('docs/'); foreach ($files as $file) { $path = 'docs/' . $file; if (file_exists($path) && is_readable($path) && (time() - filemtime($path) < 86400)) { echo $file . "\n"; } } [OK]
Hint: Combine file_exists(), is_readable(), and filemtime() with full path [OK]
Common Mistakes:
  • Not using full path when checking files
  • Ignoring file modification time condition
  • Checking is_writable() instead of is_readable()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard