PHP Content-Type Headers

PHP can send a raw HTTP header to your visitor’s browser letting it know what type of data you’re going to be passing. It’s quick, it’s easy, and it’s important if you want to make sure your non-ASCII characters don’t end up as those dreaded square boxes or gobbledygook.

Here’s the one that you shoul most likely be using:

<?php header('Content-Type: text/html; charset=utf-8'); ?>

That tells the browser that you’re sending over HTML code, and that it’s encoded as UTF-8. Then, as a backup, you can place this meta tag just after <html> in your output code:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

If you want the browser to render your code as plain text instead of HTML use this:

<?php header('Content-Type: text/plain; charset=utf-8'); ?>

And if you want your visitor to download that text, use this:

header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="download.txt"');

You can, of course, change the filename from download.txt to whatever you want it to be.

Plain text and HTML are far from the only content types you can use. Here’s a list of some popular ones:

<?php header('Content-Type: text/html; charset=utf-8'); ?>
<?php header('Content-Type: text/plain; charset=utf-8'); ?>
<?php header('Content-Type: text/css; charset=utf-8'); ?>
<?php header('Content-Type: text/csv; charset=utf-8'); ?>
<?php header('Content-Type: text/tab-separated-values; charset=utf-8'); ?>
<?php header('Content-Type: application/xml; charset=utf-8'); ?>
<?php header('Content-Type: application/rss+xml; charset=utf-8'); ?>
<?php header('Content-Type: application/pdf'); ?>
<?php header('Content-Type: image/jpeg'); ?>
<?php header('Content-Type: image/png'); ?>
<?php header('Content-Type: image/gif'); ?>

Those are all be pretty self-explanatory. There are plenty more content types out there, but I felt that this smaller list would be more helpful than a giant list that you’d have to wade through. That said, if there are other content types that you frequently use and think should be on this list, let us know in the comments below.



This post was published on January 15th, 2018 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.