Backend Development 5 min read

PHP cURL Wrapper Functions for GET, POST, and JSON Requests

This article provides PHP functions that demonstrate how to perform HTTP GET, POST, and JSON‑encoded POST requests using cURL, including error handling, timeout settings, SSL options, retry logic, and a usage example for calling an API.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP cURL Wrapper Functions for GET, POST, and JSON Requests

This note records several PHP cURL wrapper functions for making HTTP requests in different ways—GET, POST, and JSON POST—so that developers can copy or reference them in their own projects.

GET method

/**
 * Function:curl GET 请求
 * @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

/**
 * 请求一个地址
 *
 * @param   string $url 需要请求的地址
 * @param   array  $post 需要以post的方式发送的数据
 * @param   bool   $is_async 是否是异步方式请求;暂未实现
 * @param   int    $retry 重试次数;默认0
 * @param   bool   $verify_ssl 是否验证 ssl 证书;默认禁用
 * @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);

    // 需要以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); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    }

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); // 自动设置Referer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回curl获取到的内容而不是直接输出
    curl_setopt($ch, CURLOPT_HEADER, false); // 不显示返回的header内容
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5秒超时
    $content = curl_exec($ch);

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

    // 重试
    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 用json方式
 * @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();  //初始化
    curl_setopt($curl,CURLOPT_URL,$url);  //设置url
    curl_setopt($curl,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);  //设置http验证方法
    curl_setopt($curl, CURLOPT_TIMEOUT,30);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);  //设置curl_exec获取的信息的返回方式
    curl_setopt($curl,CURLOPT_POST,1);  //设置发送方式为post请求
    curl_setopt($curl,CURLOPT_POSTFIELDS,$postData);  //设置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;
}

Usage example

<?php

$apiUrl = '' ; // 请求的api的url

// 请求获取商品
$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);

After reading, you are encouraged to like and share the article as support.

JSONhttpPHPcurlGETPOST
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.