How can PHP scripts be optimized to prevent common errors like images not displaying correctly due to size changes or other factors?

To prevent common errors like images not displaying correctly due to size changes or other factors, PHP scripts can be optimized by using the `getimagesize()` function to retrieve the dimensions of an image and then dynamically adjust the HTML output based on these dimensions.

<?php
$filename = "image.jpg";
list($width, $height) = getimagesize($filename);
echo "<img src='$filename' width='$width' height='$height'>";
?>