What potential pitfalls should beginners be aware of when working with files in PHP?

Beginners should be aware of potential security vulnerabilities when working with files in PHP, such as allowing users to upload malicious files or exposing sensitive information. It is important to validate and sanitize user input, check file permissions, and avoid using user-controlled data directly in file operations to prevent these risks.

// Example of validating and sanitizing user input when working with files
$filename = $_POST['filename'];
$filename = filter_var($filename, FILTER_SANITIZE_STRING);

// Example of checking file permissions before performing file operations
if (is_writable('path/to/file.txt')) {
    // Perform file operations
} else {
    echo 'File is not writable.';
}

// Example of avoiding user-controlled data in file operations
$filepath = 'path/to/' . basename($_POST['file']);
if (file_exists($filepath)) {
    // Perform file operations
} else {
    echo 'File does not exist.';
}