PHP 'rawurlencode' 和 JS 'encodeURIComponent' 之间的不同行为是否重要?

Does it matter the different behavior between PHP `rawurlencode` and JS `encodeURIComponent`?

本文关键字:是否 之间 rawurlencode JS encodeURIComponent PHP      更新时间:2023-09-26

根据 https://stackoverflow.com/a/1734255/1529630,encodeURIComponentrawurlencode相同,但!*'()没有转义,例如,

function encodeURIComponent($str) {
    $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
    return strtr(rawurlencode($str), $revert);
}

但是,这种差异重要吗?

通常,我使用类似的东西

  • 在 JS 中
    wrapper.innerHTML = '<a href="foo.php?bar=' + encodeURIComponent(myVar) + '">Link</a>';
  • 在 PHP 中
    echo '<a href="foo.php?bar=' . rawurlencode(myVar) . '">Link</a>';

如果那么,在foo.php中,我使用$_GET['bar'],是否有可能由于encodeURIComponentrawurlencode之间的差异而得到不同的结果?

您只需要转义代码中可能具有特殊用途的字符。

例如,以下内容可用于要求代码进行数学比较或计算 -<,> , + , - ,/, =

然后是特定于 URL 创建的保留字符,例如 -?, @ , %, #

字符 !*'() 没有特殊含义,因此不会被误解,因此不需要转义。但是,您可以不必要地转义字符,因此它可能看起来像不同的结果,但它意味着/做同样的事情。

这有一个更彻底的细分 - http://www.blooberry.com/indexdot/html/topics/urlencoding.htm