我正在创建一个搜索页面,您可以在其中键入搜索查询,并将表单提交给search.php?query=your query
。什么PHP函数是最好的,我应该用于编码/解码搜索查询?
对于URI查询,请使用urlencode
/ urldecode
;其他任何使用rawurlencode
/ rawurldecode
。
urlencode
和rawurlencode
之间的区别在于
urlencode
根据application/x-www-form-urlencoded编码(空间用+
编码),而rawurlencode
根据平原Percent-Encoding编码(空间用%20
编码)。狡猾的名字urlencode()和urldecode()。
但是,您不应该在urldecode()
和$_POST
中出现的变量上使用$_GET
。
这是我的用例,需要大量的编码。也许你认为它是人为的,但我们在生产中运行它。巧合的是,这涵盖了所有类型的编码,因此我将其作为教程发布。
有人刚在我们的网站上买了一张预付礼品卡(“代币”)。令牌具有相应的URL以兑换它们。该客户希望通过电子邮件将其发送给其他人。我们的网页包含一个mailto
链接,可以让他们这样做。
// 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()
处理。
你应该看到:
"args": {
"token": "w%a&!e#\"^2(^@azW"
},
当然这是上面的$token
的JSON表示。
您可以使用PHP具有的URL编码功能
rawurlencode()
功能
ASP有
Server.URLEncode()
功能
在JavaScript中,您可以使用
encodeURIComponent()
功能。