What best practices should be followed when working with file handling and string manipulation in PHP?

When working with file handling and string manipulation in PHP, it is important to ensure proper error handling, use secure file paths, and sanitize user input to prevent security vulnerabilities. Additionally, always close files after reading or writing to them to free up resources and avoid memory leaks.

// Example of reading a file and manipulating its contents safely

$file = 'example.txt';

// Check if file exists
if (file_exists($file)) {
    // Open the file for reading
    $handle = fopen($file, 'r');

    // Read the contents of the file
    $contents = fread($handle, filesize($file));

    // Close the file
    fclose($handle);

    // Manipulate the string
    $manipulatedContents = strtoupper($contents);

    // Output the manipulated contents
    echo $manipulatedContents;
} else {
    echo 'File does not exist.';
}