How can the use of fopen, fputs, and fclose functions be optimized to prevent stream resource errors in PHP scripts?

When using fopen, fputs, and fclose functions in PHP scripts, it is important to properly handle errors related to stream resources. To prevent stream resource errors, always check the return value of fopen to ensure the file was opened successfully before performing any operations. Additionally, check the return value of fputs to verify that the data was written to the file properly. Finally, always close the file using fclose to release the resources after finishing the operations.

$file = fopen("example.txt", "w");
if ($file) {
    if (fputs($file, "Hello, World!") !== false) {
        echo "Data written successfully!";
    } else {
        echo "Error writing data to file!";
    }
    fclose($file);
} else {
    echo "Error opening file!";
}