php - 实现curl命令行到php,尝试但得到错误

时间:2012-06-28 12:22:12

标签: php curl

任何人都可以将这个在命令行中运行的curl命令转换为php代码:

$ curl -u username@gmail.com -X POST -d "" https://build.phonegap.com/token

我尝试了这段代码,但没有工作:

$target_url = "https://USERNAME@gmail.com:PASSWORD@build.phonegap.com/token"
 $ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);

$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

当我执行上面的代码时,我收到错误:

 301 Moved
 The document has moved here(link to gmail.com).

但是,如果我在命令行中使用该命令,它工作正常。我哪里错了?

另外,请告诉我这是什么" -X"意思是,如何将其转换为PHP代码?

由于

1 个答案:

答案 0 :(得分:1)

301是重定向响应代码。添加以下行:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

...在curl_init()之后和curl_exec()之前,让cURL跟随重定向到正确的位置。

-X选项用于在原始命令字符串中指定POST方法,该方法已与curl_setopt($ch, CURLOPT_POST, 1);

镜像

修改

试试这段代码:

$username = "USERNAME@gmail.com";
$password = "PASSWORD";
$target_url = "https://build.phonegap.com/token"

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

$result = curl_exec($ch);
curl_close ($ch);
echo $result;