【问题标题】:How to set default php header()如何设置默认的php header()
【发布时间】:2013-07-28 20:32:31
【问题描述】:

当我创建非英语页面(例如俄语)时,我必须使用 header() 来设置页面的字符集(我使用 UTF-8):

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

但是我所有的页面都应该有 UTF-8 字符集,php 中是否有一个属性可以默认设置它(我的意思是:我不想每次都设置它)。

【问题讨论】:

标签: php header


【解决方案1】:

您可以使用 .htaccess 文件来执行此操作:

AddDefaultCharset UTF-8

如果你想要更健壮的东西,你可以只为特定的文件类型指定这个字符集类型:

<FilesMatch ".(htm|html|css|js)$">
    AddDefaultCharset UTF-8
</FilesMatch>

另请参阅本文了解其他方法: http://www.askapache.com/htaccess/setting-charset-in-htaccess.html

【讨论】:

  • 所以,设置语言我应该使用:AddLanguage ru-Ru .html .htm .css .js,还是别的什么?
  • 是的,这应该是可能的。您还可以使用 DefaultLanguage 指令,例如DefaultLanguage en-US.
【解决方案2】:

整个 .htaccess 文件

让我们看一下整个 htaccess 配置文件,然后浏览所有配置选项。

Header unset Pragma
FileETag None
Header unset ETag

将图像/pdf 文档缓存 10 天

<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif)$">
  Header set Cache-Control "max-age=864000, public, must-revalidate"
  Header unset Last-Modified
</FilesMatch>

缓存 html/htm/xml/txt 文件 2 天

<FilesMatch "\.(html|htm|xml|txt|xsl)$">
  Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>

【讨论】:

    【解决方案3】:

    你可以使用define()设置默认字符集。

    来自 PHP 文档http://www.php.net/manual/en/regexp.reference.unicode.php

    $text = '';//some russian content
    define('CHARSET', preg_match( '/[\p{Cyrillic}]/u', $text) ? 'windows-1251' : 'utf-8');// or fetch charset from DB some other resource
    header('Content-Type: text/html; charset='.CHARSET);
    

    【讨论】:

    • 我已经说过了:我不想使用 header(),我想设置 headers 默认值!
    • 您可以使用 .htaccess 为您的页面设置默认字符集,但是当页面中使用的语言不同时您会怎么做。在这种情况下,您需要编写一些可以检测字符集的算法
    • 我的网站只有英文/俄文,所以我只需要 UTF-8(或 windows-1251)
    【解决方案4】:

    您的问题与 PHP 无关。您的 httpd 配置不正确(即,在许多发行版 Apache 上,默认情况下 AddDefaultCharset 设置为 Latin1

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2018-01-26
      • 2016-07-09
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多