What are some best practices for handling file and directory operations in PHP, especially when dealing with WordPress plugins?

When handling file and directory operations in PHP, especially within WordPress plugins, it is important to ensure proper permissions are set and to sanitize user input to prevent security vulnerabilities. Additionally, using WordPress functions for file operations can help maintain compatibility and security within the WordPress environment.

// Example of using WordPress functions for file operations
$file_path = WP_PLUGIN_DIR . '/my-plugin/my-file.txt';

// Check if file exists
if (file_exists($file_path)) {
    // Read file contents
    $file_contents = file_get_contents($file_path);
    
    // Write to file
    file_put_contents($file_path, 'New content');
    
    // Delete file
    unlink($file_path);
}