从php脚本到浏览器,编码方式浅析

今天简单看了一下php,服务器,浏览器如何设定编码

1.php

在php配置文件php.ini中,可以设置字符编码

; PHP's default character set is set to empty.
; http://php.net/default-charset
default_charset = "gb2312"

在PHP 5.6及其之后,"UTF-8"是缺省值(5.6之前是空值),对于以下函数:htmlentities(), html_entity_decode() and htmlspecialchars() ,如果他们的编码参数被省略了,则default_charset的值用于这些函数的默认编码.对于 iconv函数,如果其参数input_encoding 3.output_encoding/internal_encoding等没有设置的话,也会采用default_charset的值,对于mbstring函数,如果mbstring.http_input mbstring.http_output mbstring.internal_encoding没有设置的话,也会采取default_charset的值,

另外,不推荐将default_charset设为空值.(Setting default_charset to an empty value is not recommended).

脚本的编码类型一定要和default_charset一致,否则会乱码的.

2.服务器(如apache)在返回响应头content-type时,会参照php.ini的设定,

比如:

//php.ini中
default_charset = "aaabbccc"
查看响应头:
Content-Type: text/html; charset=aaabbccc

如果php脚本中使用了header函数,则服务器的响应头会遵循header函数的设定.

 3.关于相应实体中的meta设置content-type

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

它的优先级是低于响应头中规定的content-type的,也就是说响应头中规定了编码类型,则浏览器会遵循响应头的设定(一般是这样,最终决定权在浏览器手中)

4.浏览器编码设定

对比了一下chrome,ff,360浏览器,ie8,发现chrome浏览器好像无视用户的手动设定,具体机制不明白,而其他浏览器,只要用户更改了编码,则会按用户指定编码去解码

原文地址:https://www.cnblogs.com/ch459742906/p/6000705.html