【问题标题】:White spaces in postFields in PHP CurlPHP Curl中postFields中的空格
【发布时间】:2012-05-02 01:39:11
【问题描述】:

我有下一个代码:

$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.mydomain.com/test.php');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS,"First Name=Jhon&Last Name=bt");
curl_exec ($c);
curl_close ($c);

我的问题是这段代码中的空格:

"First Name=Jhon&Last Name=bt"

我尝试了下一个代码:

$test=rawurlencode("First Name=Jhon&Last Name=bt");

$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.mydomain.com/test.php');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS,$test);
curl_exec ($c);
curl_close ($c);

我也试过了

$first_name=rawurlencode("名字");

$last_name=rawurlencode("姓氏");

$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.mydomain.com/test.php');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS,"$first_name=Jhon&$last_name=bt");
curl_exec ($c);
curl_close ($c);

我的错误是什么?不管用。我需要使用变量“名字”和“姓氏”的名称发送。感谢您的帮助。

【问题讨论】:

  • 在下面查看我的更新答案。如果您从变量名中删除引号并正确连接,您的解决方案可能会起作用。

标签: php curl libcurl


【解决方案1】:

独立 curl 编码。

http://curl.haxx.se/docs/manpage.html#--data-urlencode

PHP urlencoding

只需先对值进行编码,然后将其作为 post 字段选项传递给 curl。

$encodedValue = urlEncode("this has spaces - oh no!");
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.mydomain.com/test.php');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS , "value=" . $encodedValue);
curl_exec ($c);
curl_close ($c);

或者,如果你的 key 有空格:

 $encodedKey = urlEncode("first name");
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, 'http://www.mydomain.com/test.php');
    curl_setopt($c, CURLOPT_POST, true);
    curl_setopt($c, CURLOPT_POSTFIELDS , $encodedKey . "=Bobby");
    curl_exec ($c);
    curl_close ($c)

【讨论】:

  • 感谢您的回答。我已经查看了链接,但我不明白如何使用我的示例进行操作。我尝试使用 urlenconde("First Name=Jhon&Last Name=bt") 并且无法正常工作。感谢您的帮助。
  • 我的错,我看到您使用的是 PHP 的 cURL: 库,而不是独立的 curl 实用程序。只需利用 PHP 的 urlencode 命令。
  • 您不能在变量名称中使用空格,如果您在 php 端的 捕获它
猜你喜欢
  • 2020-11-10
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2014-04-18
相关资源
最近更新 更多