在php脚本中使用curl

我正在尝试创建一个脚本,删除特定个人的所有用户属性.我可以使用api调用来获取用户的属性.我正在尝试使用删除api删除每个属性.但我有一个问题.以下是代码:

$delete = "http://www.ourwiki.com/@api/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);

foreach($xml->property as $property) {
  $name = $property['name']; // the name is stored in the attribute
  file_get_contents(sprintf($delete, $name));
}

我相信我需要使用curl来执行实际删除.以下是该命令的示例(property = something):

curl -u username:password -X DELETE -i http://ourwiki.com/@api/users/=john_smith@ourwiki.com/properties/something

-u提供外部用户身份验证.

-X指定HTTP请求方法.

-i输出HTTP响应头.对调试很有用.

这是我可以合并到现有脚本中的东西吗?或者我还需要做些什么吗?任何帮助将不胜感激.

更新:

<?php

$user_id="john_smith@ourwiki.com";

$url=('http://aaron:12345@192.168.245.133/@api/deki/users/=john_smith@ourwiki.com/properties');
$xmlString=file_get_contents($url);

$delete = "http://aaron:12345@192.168.245.133/@api/deki/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);

 function curl_fetch($url,$username,$password,$method='DELETE')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
    curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
    return  curl_exec($ch);
}

foreach($xml->property as $property) {
  $name = $property['name']; // the name is stored in the attribute
  curl_fetch(sprintf($delete, $name),'aaron','12345');
}

?>

最佳答案 您可以使用
php curl,或使用
exec外壳卷曲.

如果您的Web服务器上已经启用了curl,请使用php curl.如果你不能安装php-curl复制curl的命令行版本,你很高兴.

在php-curl中设置delete方法:

curl_setopt($ch,CURLOPT_CUSTOMREQUEST,’DELETE’);

编辑

像这样的东西:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.ourwiki.com/@api/whatever/url/you/want/or/need");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
$output = curl_exec($ch);

EDIT2

在函数中坚持上面的代码:

function curl_fetch($url,$username,$password,$method='DELETE')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
    curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
    return  curl_exec($ch);
}

并使用新函数替换脚本中对file_get_contents()的调用.

curl_fetch(sprintf($delete,$name),’aaron’,’12345′);

完成.

点赞