The .jpg and .jpeg Mime Type

Tutorial on delivering jpeg files with the correct mime type and headers using PHP.

8970 views

Edited: 2019-12-02 20:55

JPEG and JPG mime type, PHP

The correct content-type to use for delivering jpeg image files over the HTTP protocol is image/jpeg. The standard file extension for jpeg images is .jpeg, but .jpg is also broadly supported.

A HTTP response to deliver a jpeg image can look like this:

HTTP/1.1 200 OK
content-type: image/jpeg
content-length: 39354

Note. A character-set is not needed for image files.

To use the image/jpeg Mime Type from a PHP script, use the header function:

header('content-type: image/jpeg');
// Body output after this point

Deliver JPEG files from PHP

Reading a local file into a variable can be done using file_get_contents, but this is impractical for larger files. After reading the content of a file, you can output it with echo.

While this below example works, there are many potential issues depending on the circumstances, so you should not use this without taking additional steps:

// Path to file
$file_path = '/var/www/test.jpeg';

// Obtain file size for the content-length header
$file_size = filesize($file_path);

// Read the content from the file
$jpeg_file = file_get_contents($file_path);

header('content-length: ' . $file_size);
header('content-type: image/jpeg');
echo $jpeg_file;

JPEG vs JPG

The .jpg and .jpeg are both jpeg image files. The original extension used was .jpeg, but early Windows versions used .jpg, and many now prefer the 3 letter file extension as a result.

Browsers will accept the image/jpeg Mime Type for both file types. The image/jpg Mime Type does not exist.

Instead of using jpeg images, you may want to consider using the new webp format, as it offers better compression.

Editing JPEG files

You can edit .jpeg files using an editor such as Gimp or Paint.NET.

Gimp works well in both Windows and Linux, check gimp.org for the latest version.

Paint.NET works best in Windows, find it here: getpaint.net.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials