如何使用 php 发送 curl 请求

How do I send curl request with php

如何使用 php

发送以下 curl 请求
$ curl -X POST -u "client_id:secret" https://bitbucket.org/site/oauth2/access_token 
-d grant_type=authorization_code -d code={code}
<?php
 if ($curl = curl_init()) {
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_URL, 'http://mysite.ru/');
    curl_setopt($curl, CURLOPT_USERPWD, "client_id:secret");
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, "code=someCode&");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $return  = curl_exec($curl);
    curl_close($curl);
}
?>

link

使用 GuzzleHttp。

<?php
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://bitbucket.org/site/oauth2/access_token', [
    'auth' => ['client_id', 'secret'],
    'form_params' => [
        'grant_type' => 'authorization_code',
        'code' => 'code'
    ]
]);
$code = $response->getStatusCode(); // must be 200
$reason = $response->getReasonPhrase(); // must be OK
$body = (string) $response->getBody(); // must have your data

注意,如果你实现的是OAuth Client,强烈推荐使用开源库:

步骤1)初始化CURLsession

    $ch = curl_init();

步骤 2) 为 CURL session

提供选项

curl_setopt($ch,CURLOPT_URL,"http://akshayparmar.in");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,真);

//curl_setopt($ch,CURLOPT_HEADER, true); //如果你想要headers

CURLOPT_URL -> URL 获取

CURLOPT_HEADER -> 包括 header/not

CURLOPT_RETURNTRANSFER -> 如果设置为 true,数据将作为字符串返回而不是输出。

有关选项的完整列表,请查看 PHP 文档。

步骤3).执行CURLsession

    $output=curl_exec($ch);

步骤 4)。关闭session

curl_close($ch);

注意:可以用下面的代码查看是否CURLenabled/not

if(is_callable('curl_init'))

{

回声"Enabled";

}

其他

{

回声"Not enabled";

}

  1. PHP CURL 获取示例:- 您可以使用以下代码发送 GET 请求。

函数 httpGet($url) {

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output=curl_exec($ch);
curl_close($ch);
return $output;

}

echo httpGet("http://akshayparmar.in");