search
HomeBackend DevelopmentPHP TutorialNodejs如何处理IE诡异的非英文URL编码

众所周知URL里是不能出现除了英文数字和某些特殊符号外的其他字符的,也不能出现汉字。URL会出现汉字也就4种情况:

  1. 网址路径(path)中包含汉字:如 https://zh.wikipedia.org/wiki/浏览器
  2. Get方法生成包含汉字的URL:一般是由表单生成的,比如 https://zh.wikipedia.org/w/index.php?search=%E6%B5%8F%E8%A7%88%E5%99%A8
  3. 查询字符串(Query String)包含汉字:比如 https://zh.wikipedia.org/w/index.php?search=浏览器 与第二种不同的是直接在浏览器地址栏输入汉字
  4. Ajax调用的URL包含汉字: 比如 <script>url = url + "?q=" +document.getElementById("input").value;</script>

在第一种情况下,各浏览器始终使用UTF-8编码,也就是最后被解析成了 https://zh.wikipedia.org/wiki/%E6%B5%8F%E8%A7%88%E5%99%A8
第二种情况则是根据当前页面编码进行转义,2中的例子用的就是UTF-8
第三种情况就相当诡异了,Chrome和FF都使用UTF-8进行转义,而IE则不是。查了一下,IE用的是操作系统的默认编码,据我所知这个默认编码在不同Windows版本和不同系统语言下都不一样。
第四种情况和第三类似,IE使用系统默认而Chrome和FF使用UTF-8。

于是乎服务器拿到第三和第四种的请求后,根本不知道用的是什么编码。第四种倒容易解决,提前用JavaScript指定编码转义一次就好。但是第三种就...

于是说服务器如何确定在第三种情况发来的发来的查询字符串真正内容?这里用的是Nodejs,可以的话也想听听PHP的解决方案。

试了一个貌似在IE下,用第三种情况搜索Wordpress也会返回404(用错误解码方式的关键词查询数据库没有找到结果)。

=============
突然想到一个点子,能不能从请求header的UA判断是否为IE,如果是再通过Accept-Language来猜测编码...(我开始乱来了....

回复内容:

众所周知URL里是不能出现除了英文数字和某些特殊符号外的其他字符的,也不能出现汉字。URL会出现汉字也就4种情况:

  1. 网址路径(path)中包含汉字:如 https://zh.wikipedia.org/wiki/浏览器
  2. Get方法生成包含汉字的URL:一般是由表单生成的,比如 https://zh.wikipedia.org/w/index.php?search=%E6%B5%8F%E8%A7%88%E5%99%A8
  3. 查询字符串(Query String)包含汉字:比如 https://zh.wikipedia.org/w/index.php?search=浏览器 与第二种不同的是直接在浏览器地址栏输入汉字
  4. Ajax调用的URL包含汉字: 比如 <script>url = url + "?q=" +document.getElementById("input").value;</script>

在第一种情况下,各浏览器始终使用UTF-8编码,也就是最后被解析成了 https://zh.wikipedia.org/wiki/%E6%B5%8F%E8%A7%88%E5%99%A8
第二种情况则是根据当前页面编码进行转义,2中的例子用的就是UTF-8
第三种情况就相当诡异了,Chrome和FF都使用UTF-8进行转义,而IE则不是。查了一下,IE用的是操作系统的默认编码,据我所知这个默认编码在不同Windows版本和不同系统语言下都不一样。
第四种情况和第三类似,IE使用系统默认而Chrome和FF使用UTF-8。

于是乎服务器拿到第三和第四种的请求后,根本不知道用的是什么编码。第四种倒容易解决,提前用JavaScript指定编码转义一次就好。但是第三种就...

于是说服务器如何确定在第三种情况发来的发来的查询字符串真正内容?这里用的是Nodejs,可以的话也想听听PHP的解决方案。

试了一个貌似在IE下,用第三种情况搜索Wordpress也会返回404(用错误解码方式的关键词查询数据库没有找到结果)。

=============
突然想到一个点子,能不能从请求header的UA判断是否为IE,如果是再通过Accept-Language来猜测编码...(我开始乱来了....

这个问题和IE没多大关系...
btw: 你后面提到的 通过Accept-Language来猜测编码更是不靠谱.
因为这个 请求头是 告诉服务器 浏览器支持什么样的语言(Language), 与本次提交时参数的编码没有任何关系.

你遇到的问题, 主要是后端的编码识别的问题.

测试代码:
1.html 文档声明内容编码为 utf-8, 且文件保存编码为 utf-8.
不管是在IE还是Chrome,Firefox下, 点按钮提交的汉字均为utf-8编码.

<code>

 
  <meta charset="utf-8">
 

 


<form action="http://www.baidu.com/s" method="GET">
  <input type="text" name="wd" value="浏览器">
  <input type="submit">
  </form>


 

</code>

2.html 文档声明内容编码为 gb2312, 且文件保存编码为 gb2312.
不管是在IE还是Chrome,Firefox下, 点按钮提交的汉字均为gb2312编码.

<code>

 
  <meta charset="gb2312">
 

 


<form action="http://www.baidu.com/s" method="GET">
  <input type="text" name="wd" value="浏览器">
  <input type="submit">
  </form>


 

</code>

上面两种编码提交到 www.baidu.com 进行搜索时, 百度均可识别出来正确的汉字.

GB2312编码时的URL地址: http://www.baidu.com/s?wd=%E4%AF%C0%C0%C6%F7
UTF-8编码时的URL地址: http://www.baidu.com/s?wd=%E6%B5%8F%E8%A7%88%E5%99%A8

认清楚问题之后, 就可以去找正确的答案了:
百度搜索关键字PHP 汉字 编码 识别(Google被墙,所以只能用百度代替了)
由编码识别遇到问题,思考utf8编码正则表达式(php版本)

将上面的测试代码的action指向下面这个php文件.
你会发现不管是 GB2312 编码提交过来的数据, 还是 UTF-8 编码提交过来的数据, 都可以正确显示所提交的汉字.

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

$wd = $_GET['wd'];

if(checkUtf8($wd) == 0){
    $wd = iconv('gbk', 'utf-8', $wd);
}

echo $wd;



function checkUtf8($str,$extzh=1)
{
    ///utf8编码正则检测函数
    ///copyright qq:8292669
    ///author  程默  http://www.cnblogs.com/chengmo

    //gbk,utf8重叠的范围是:[c0-df][a0-bf] 这块字符在utf8中有,在gbk编码没有对应字符因此向gbk转换会出现"?"号
    if($extzh==1)
    {
        $re='/^([\x01-\x7f]|[\xc0-\xdf][\xa0-\xbf])+$/';  ///这部分字符如果当作utf8处理,在转换为gbk时候就会出现问题"?"号。因此直接返回不为utf8
        if(preg_match($re,$str))  ///公共字符验证成功
        {
            return 0;  ///不是utf8
        }
    }
    $re='/^([\x01-\x7f]|[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3}|[\xf8-\xfb][\x80-\xbf]{4}|[\xfc-\xfd][\x80-\xbf]{5})+$/';
    return preg_match($re,$str);
}

</code></code>

Nodejs如何处理IE诡异的非英文URL编码

Nodejs如何处理IE诡异的非英文URL编码

这里是以PHP为例, nodejs 与此类似.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool