【问题标题】:How do I send curl request with php [closed]如何使用 php 发送 curl 请求 [关闭]
【发布时间】:2020-04-05 19:43:28
【问题描述】:

如何使用 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 curl guzzle


【解决方案1】:

使用 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 客户端,我强烈建议您使用开源库:

【讨论】:

    【解决方案2】:
    <?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

    【讨论】:

    • 你没有设置网址
    【解决方案3】:

    步骤 1) 初始化 CURL 会话

        $ch = curl_init();
    

    步骤 2) 为 CURL 会话提供选项

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

    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

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

    CURLOPT_URL -> 要获取的 URL

    CURLOPT_HEADER -> 包含标题/不包含

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

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

    步骤 3). 执行 CURL 会话

        $output=curl_exec($ch);
    

    第 4 步)。关闭会话

    curl_close($ch);
    

    注意:您可以使用以下代码检查 CURL 是否启用。

    if(is_callable('curl_init'))

    {

    回显“启用”;

    }

    其他

    {

    回显“未启用”;

    }

    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");

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 2013-12-09
      • 1970-01-01
      • 2020-10-10
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      相关资源
      最近更新 更多