PHP and curl adopt get, post and JSON request APIs

Time:2022-5-14

Record curl in different ways: get, post, JSON, etc. request an API. There are many examples on the Internet. I also write a note here to record the curl methods of requesting API in different ways. Methods can be used for reference

Get method

/**
 *Function: curl get request
 * @param $url
 * @param array $params
 * @param int $timeout
 * @return mixed
 * @throws Exception
 */
public function request_curl_get($url, $params = array(),$timeout=30){

    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    $file_contents = curl_exec($ch);
    if($file_contents === false){
        throw new Exception('Http request message :'.curl_error($ch));
    }

    curl_close($ch);
    return $file_contents;

}

Post method

/**
 *Request an address
 *
 *@ param string $URL requires the requested address
 *@ param array $post data to be sent by post
 * @param   bool $is_ Whether async is an asynchronous request; Not implemented yet
 *@ param int $retry retries; Default 0
 * @param   bool $verify_ Whether SSL verifies the SSL certificate; Disabled by default
 * @return  mixed|string
 */
function request_url($url, $post = array(), $is_async = FALSE, $retry = 0, $verify_ssl = false)
{
    if (empty($url)) return '';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    //Data to be sent by post
    if (!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($post) ? http_build_query($post): $post);
    }

    // HTTPS
    if (!$verify_ssl) {
        curl_ setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //  Inspection of the source of certification certificate
        curl_ setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //  Check whether the SSL encryption algorithm exists from the certificate
    }

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_ setopt($ch, CURLOPT_AUTOREFERER, true); //  Automatically set referer
    curl_ setopt($ch, CURLOPT_RETURNTRANSFER, true); //  Return the content obtained by curl instead of direct output
    curl_ setopt($ch, CURLOPT_HEADER, false); //  The returned header content is not displayed
    curl_ setopt($ch, CURLOPT_TIMEOUT, 5); //  5 seconds timeout
    $content = curl_exec($ch);

    if($content === false){
        throw new Exception('Http request message :'.curl_error($ch));
    }

    //Try again
    if ($retry > 0 && $content === false) {
        $try = 0;
        do {
            $content = curl_exec($ch); ++$try;
        }
        while ($content === false && $try <= $retry);
    }

    curl_close($ch);
    return $content;
}

JSON method

/**
 *Function: curl post in JSON mode
 * @param $url
 * @param array $postData
 * @return mixed|string
 * @throws Exception
 */
function api_request_curl($url, $postData = array()) {

    if (empty($url)) return '';
    $postData = json_encode($postData);

    $curl = curl_ init();  // initialization
    curl_ setopt($curl,CURLOPT_URL,$url);  // Set URL
    curl_ setopt($curl,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);  // Set HTTP authentication method
    curl_setopt($curl, CURLOPT_TIMEOUT,30);
    curl_ setopt($curl,CURLOPT_RETURNTRANSFER,1);  // Set curl_ Return method of information obtained by Exec
    curl_ setopt($curl,CURLOPT_POST,1);  // Set the sending method to post request
    curl_ setopt($curl,CURLOPT_POSTFIELDS,$postData);  // Set the data of post

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($postData))
    );

    $result = curl_exec($curl);
    if($result === false){
        throw new Exception('Http request message :'.curl_error($curl));
    }

    curl_close($curl);
    return $result;
}

Call example

<?php

$apiUrl = '' ; // URL of the requested API

//Request for goods
$param['shop_name'] = 'ALL';
$api_shop_url = $apiUrl .'/api/shop';
$shop_complete = $this->api_request_curl($api_shop_url, $param);
$res_complete_shop = json_decode($shop_complete, true);

dd($res_complete_shop);


Systematic learning PHP

In wechat official account: PHP self study center, reply to the corresponding keywords and receive the following video tutorials
1 Vue2. 5 core technology source code analysis
Key words: 19082201

2 example analysis and in-depth interpretation of design mode
Key words: 20190714

3. Complete collection of PHP advanced practical tutorials
Key words: 20190625

4 zero distance contact with MySQL
Key words: 20190128

5 high performance Linux server construction practice
Key words: 20190622

6. Analysis of the underlying source code of thinkphp5
Key words: 20190621

7 ThinkPHP plug-in development wechat system
Key words: 201907282319

8. Introduction to laravel foundation and actual development of wechat mall
Key words: 08250045

9 PHP asynchronous communication framework swoole actual combat
Key words: 08250024

For more tutorial keywords, please pay attention to the articles and tutorials shared by official account every day
PHP and curl adopt get, post and JSON request APIs

This work adoptsCC agreement, reprint must indicate the author and the link to this article


reminder: wechat search and followLearn from laravelIt is found that there are two sets of laravel courses: [laravel 7. X from introduction to core architecture] and [42 sets of laravel advanced practical tutorial]

Recommended Today

Redux Getting Started Guide (II)

Author: jogisOriginal link:https://github.com/yesvods/Blog/issues/7For reprint, please indicate the original link and author information The first part introduces the core idea of Redux as a state containerstateInitialization, toactionBe distributed and change state. The subsequent extensions focus on the core idea, and are also benefiting from other extensions such as functional programming. Redux has become the most popular […]