如何在PHP中正确地对字符串进行URL编码?

时间:2011-01-20 08:31:46

标签: php urlencode

我正在创建一个搜索页面,您可以在其中键入搜索查询,并将表单提交给search.php?query=your query。 PHP函数最好用于编码/解码搜索查询?

5 个答案:

答案 0 :(得分:156)

对于URI查询,请使用urlencode / urldecode;其他任何使用rawurlencode / rawurldecode

urlencoderawurlencode之间的区别在于

答案 1 :(得分:18)

狡猾的urlencode()urldecode()

但是,您不需要对urldecode()$_POST中显示的变量使用$_GET

答案 2 :(得分:7)

这是我的用例,需要大量的编码。也许你认为它是人为的,但我们在生产中运行它。巧合的是,这涵盖了所有类型的编码,因此我将其作为教程发布。

用例说明

有人刚刚在我们的网站上购买了预付礼品卡("令牌")。令牌具有相应的URL以兑换它们。该客户希望通过电子邮件将其发送给其他人。我们的网页包含mailto链接,可让他们这样做。

PHP代码

// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';

// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);

// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'I just bought a widget for you. Please enter your shipping details here: ' . $redeemUrl;

// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);

// Print an HTML element that links to that page
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';

注意:以上假设您输出的是text/html文档。如果您的输出媒体类型为text/json,则只需使用$retval['url'] = $mailToUri;,因为输出编码由json_encode()处理。

测试用例

  1. 在PHP测试网站上运行代码(是否存在我应该在此提及的规范?
  2. 点击链接
  3. 发送电子邮件
  4. 收到电子邮件
  5. 点击该链接
  6. 您应该看到:

    "args": {
      "token": "w%a&!e#\"^2(^@azW"
    }, 
    

    当然,这是上面$token的JSON表示。

答案 3 :(得分:0)

您可以使用PHP具有的URL编码功能

rawurlencode() 

功能

ASP具有

Server.URLEncode() 

功能

在JavaScript中,您可以使用

encodeURIComponent() 

功能。

答案 4 :(得分:0)

根据要执行的RFC标准编码类型,或者如果需要自定义编码,则可能要创建自己的类。

/**
 * UrlEncoder make it easy to encode your URL
 */
class UrlEncoder{
    public const STANDARD_RFC1738 = 1;
    public const STANDARD_RFC3986 = 2;
    public const STANDARD_CUSTOM_RFC3986_ISH = 3;
    // add more here

    static function encode($string, $rfc){
        switch ($rfc) {
            case self::STANDARD_RFC1738:
                return  urlencode($string);
                break;
            case self::STANDARD_RFC3986:
                return rawurlencode($string);
                break;
            case self::STANDARD_CUSTOM_RFC3986_ISH:
                // Add your custom encoding
                $entities = ['%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'];
                $replacements = ['!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"];
                return str_replace($entities, $replacements, urlencode($string));
                break;
            default:
                throw new Exception("Invalid RFC encoder - See class const for reference");
                break;
        }
    }
}

使用示例:

$dataString = "https://www.google.pl/search?q=PHP is **great**!&id=123&css=#kolo&email=me@liszka.com)";

$dataStringUrlEncodedRFC1738 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC1738);
$dataStringUrlEncodedRFC3986 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC3986);
$dataStringUrlEncodedCutom = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_CUSTOM_RFC3986_ISH);

将输出:

string(126) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP+is+%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(130) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP%20is%20%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(86)  "https://www.google.pl/search?q=PHP+is+**great**!&id=123&css=#kolo&email=me@liszka.com)"

*了解有关RFC标准的更多信息: https://datatracker.ietf.org/doc/rfc3986/urlencode vs rawurlencode?