Best ?php header format

3 posts by 2 authors in: Forums > CMS Builder
Last Post: March 4, 2011   (RSS)

By macwebster - March 3, 2011

I recently upgraded an older cmsb site and I noticed that when I generated new pages the opening code was:

?php header('Content-type: text/html; charset=utf-8'); ?>
<?php and so forth.

my older pages started straight off with <?php

As I am adding the code generator code to Dreamweaver templates, I already have the usual meta tag with:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

When testing my pages, I see the warning message:

<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/straffor/public_html/beta/ecdev/ecdev_vision.php:2) in <b>/home/straffor/public_html/beta/ecdev/ecdev_vision.php</b> on line <b>2</b><br />

Can you explain what's going on with the php headers or am I getting the warning from another cause?

http://strafford.org/beta/ecdev/ecdev_vision.php

I know that when I remove ?php header('Content-type: text/html; charset=utf-8'); ?> the warning goes away -- on this page.

However, on some other pages I'm developing, they display properly with the php header.

can you explain what's going on? thanks in advance

J

Re: [macwebster] Best ?php header format

By Dave - March 3, 2011

Hi macwebster,

The header() line we're sending is for telling the browser what charset to display the page in. If you've ever seen a page with boxes or funny symbols instead of the proper characters it's because the wrong charset is being used.

To keep thing consistent we use a charset called utf-8 in the CMS and on display pages to ensure everything looks as it should. utf-8 supports english and non-english characters. There's lots of charsets specific to Mac, Windows and various languages, but utf-8 pretty much handles everything which is why we use it.

Usually the browser will detect this and display in UTF-8 anyways. And if it doesn't, your meta line here usually will work: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

But some web hosts force-send a different charset that overrides that meta http-equiv and confuses the browser into displaying in the wrong charset. So just to be extra safe for those few web hosts we send this additional header: <?php header('Content-type: text/html; charset=utf-8'); ?>

Now because headers are sent to the browser before anything else they can't have any content before them. From the looks of your error if sounds like you have an extra <br/> or some whitespace (returns or spaces) at the top. If you remove it the error should go away. Or just remove the header() line since you probably don't need it on your host anyway. As long as everything is displaying ok you'll know you're fine.

Hope that helps! Let me know any other questions.
Dave Edis - Senior Developer
interactivetools.com