开发者

Where to put PHP encoding type header?

I am learning about handling UTF8 character sets and the recommendation is to explicitly set the encoding type in the output headers within your PHP script like so:

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

My question is about where I should place this header.开发者_StackOverflow社区 I have a config file that is included into every script and is run first. Should I place it at the top of that file so that this header is included first in every php file?

Will that affect my ability to set other headers, including a header location redirect down the line? Or should I place this just before any html output, such as the rendering of my template file? Ie- can this header be in place before ALL other php processing, and what are the consequences of doing that? Does it affect anything server side, or just the encoding of the output?

Thanks.!


Although early setting of this header will not affect anything server-side nor other types of headers, your question being asked out of assumption that the only content your code going to output is of html type.

However, general PHP application sometimes outputs content of some other types, like application/pdf, application/excel or whatever.

Thus, sending it just before html output seems to be exactly the right place.


The only constraint you have is not to output anything (print, echo, ...) before you call the header function. Apart from this, you can call that function anywhere you want to and any number of times (you can set other headers afterwards).


I'm only recommending this as an alternative. But the setting can be fixated in the php.ini using:

default_mimetype = "text/html; charset=UTF-8"

It's less common on shared hosters, where some of the users might depend on L1. But if you use your own server and want to ensure that it's correctly set regardless of code and whichever PHP script is invoked, then this is your option.


You can put the header directive anywhere prior to when you start sending page text. The order relative to other headers is not supposed to matter; however, if you have sent even one character of page text, PHP will give you an error.

Note that "sending page text" can sometimes happen inadvertently due to another error message or due to a space before or after <?php ?> tags, etc.


As long as it is inside the -tags and BEFORE you create any output (echo, print, print_r and so on - or any HTML BEFORE the -tags).

OKAY METHOD:

<?php
$var = "hello world";
$var2 = "Goodbye world!";

header();

echo $var2;
?>

OKAY METHOD:

<?php
header();
$var = "hello world";
$var2 = "Goodbye world!";



echo $var2;
?>

NOT OKAY METHOD:

<?php
$var = "hello world";
$var2 = "Goodbye world!";

echo $var2;
header();
?>

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜