使用PHP curl时,具有单引号的Post值会导致问题


post values having single quote lead to issue while using php curl

我必须使用curl将字符串内带有单引号的值发布到 url 中,单引号自动剥离我认为,如何在使用curl时正确包含字符串中的单引号,

$url = "test.com/req?a=10&b='1010','1012'";  
$ch = curl_init();  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_HEADER, 0);  
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
$result = curl_exec($ch);  
curl_close($ch);  

使用 urlencode。

$url = "test.com/req?a=10&b=" . urlencode("'1010','1012'");

通过这种方式,您可以构建任何复杂程度的查询字符串:

$url   = 'test.com/req';
$query = array(
  'a' => 10,
  'b' => "'1010','1012'"
);
$url .= '?'. http_build_query($query);
// will produce this
// test.com/req?a=10&b=%271010%27%2C%271012%27