Change In File Mime Type – My PHP Story

I shared previously how I easily downloaded all images in a webpage without having to individually download each image.
I got inspired by it and I decided to build a simple web tool using PHP that scrap and download and archive all images found in a specified webpage in ZIP format. It isn’t production ready yet as it’s still in Alpha stage.

While building the tool, I discovered a mistake by me which added a newline /n after the image name led to the change in the image MIME type to text/x-generic instead of the correct image/x-generic thereby corrupting the image.

Below is a code extract from the PHP class that loop through all images in the webpage.


foreach($html->find('img') as $image) {
    $result[] = $image->src . "\n";

}

Did you see the \n appended to the image names $image->src?

After hours of unsuccessful debugging, I decided to upload it to my shared web hosting server thinking maybe it was because am on a localhost. Oh No! same shit happened.
Trying to open the image via the image URL always lead to a 404 error not found when actually the file does exist.

Removing the space and/or newline suffix from the image name fixed the problem and the images was rendering properly.

Summary

From the piece above, we found out that any form of newline or space after an image or any file name, alters it MIME type which in-turn corrupt the file or/and lead to an error in your code.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address