任何人都可以将这个在命令行中运行的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代码?
由于
答案 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;