php - 使用 Curl 在 PHP 中使用用户名和密码访问 API

标签 php json url zendesk-api

这是示例代码,但在 cmd 上使用 Curl:

curl https://www.zopim.com/api/v2/chats -u {username}:{password}

我如何在 PHP 中查询它?

最佳答案

可能会在 How to use basic authorization in PHP curl 上回答 所以从那里尝试:

<?php
$username='username';
$password='pass';
$URL='https://www.zopim.com/api/v2/chats';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

打印或显示 json 使用:

$obj = json_decode($result);
print $obj->{'user'}; 
echo $obj->{'message'}; 

关于php - 使用 Curl 在 PHP 中使用用户名和密码访问 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44771350/

相关文章:

gd库的php路径

php - 使用 Gears 和 PHP 上传文件

php - 使用数据泵 api 从 mysql 将产品导入到 magento 非常慢

node.js - IBM Watson 个性洞察服务 : giving bad request as response

javascript - .NET Core ViewModel 中的 IFormFile 属性导致 AJAX 请求停滞

javascript - 在 angularjs 中处理 json 响应(来自 PHP 和 mysql)

javascript - 仅使用 HTML 将参数传递给 <a> href 标记内的链接

php - 使用 PostgreSQL 以简单的方式获取所有父项

javascript - 如何获取url AngularJS的最后一部分

jquery - 使用 URL 哈希和 jQuery 处理单页网站并维护状态