curl_escape

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_escape使用 URL 编码给定的字符串

说明

curl_escape ( resource $ch , string $str ) : string

该函数使用 URL 根据» RFC 3986编码给定的字符串。

参数

handle

curl_init() 返回的 cURL 句柄。

str

需要编码的字符串

返回值

返回编码后的字符串 或者在失败时返回 false

范例

Example #1 curl_escape() 示例

<?php
// 创建一个 curl 句柄
$ch curl_init();

// 把编码后的字符串当做一个 GET 参数
$location curl_escape($ch'Hofbr?uhaus / München');
// 结果: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// 用编码好的字符串组装一个 URL
$url "http://example.com/add_location.php?location={$location}";
// 结果: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// 发送 HTTP 请求并关闭句柄
curl_setopt($chCURLOPT_URL$url);
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_exec($ch);
curl_close($ch);
?>

参见

User Contributed Notes

sam dot tyurenkov at gmail dot com 24-May-2020 12:19
Please someone add an example for escaping ampersands between parameters.

E.g. what is the correct approach for using this URL with curl:
https://example.com/?p1=1&p2=2&p3=3

This is not obvious, and needs explanation.
Franois 10-Oct-2014 09:45
This function is strictly equivalent to rawurlencode().

Internally it uses curl_easy_escape() from libcurl, whose doc says: "This function converts the given input string to an URL encoded string (...). All input characters that are not a-z, A-Z, 0-9, '-', '.', '_' or '~' are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number)."
Nico 29-Sep-2014 01:51
What is difference between this function and urlencode()?