PHP HTTP Client Utility Using cURL – Practical Example and Story

The author describes receiving a paid PHP development request, quickly implementing a cURL‑based HTTP client class to handle GET, POST, PUT, and DELETE requests with JSON payloads, and shares the full code to help others solve similar integration problems.

php Courses
php Courses
php Courses
PHP HTTP Client Utility Using cURL – Practical Example and Story

The author recounts how, over a weekend, they were approached in a QQ group for paid PHP development assistance, accepted the task, and completed it by adapting existing code to meet the client’s request.

They explain that the technical challenge was to simulate an HTTP request in PHP, and they provide a reusable HttpClientUtil class that uses cURL to send GET, POST, PUT, and DELETE requests with JSON data, handling SSL verification, custom headers, and response parsing.

The full implementation is presented below, including the class definition, sendRequest method, createSign helper for signing data, and an example usage with sample request parameters.

<?php
class HttpClientUtil
{
    public function sendRequest($type = '', $url = '', $data = [], $timeout = 60)
    {
        try {
            $type = strtoupper($type);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url); //设置请求链接
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //不直接输出页面
            curl_setopt($curl, CURLOPT_HEADER, 0); //获取响应头向下
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   //请求超时时间,单位:秒
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
            if (substr($url, 0, 5) == 'https') { //自动判断是否是https提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  // https请求 不验证证书和hosts
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
            switch ($type) {
                case "GET" :
                    curl_setopt($curl, CURLOPT_HTTPGET, true);
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    break;
                case "PUT" :
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    break;
                case "DELETE":
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    break;
            }
            $result = curl_exec($curl);
            $err_code = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            curl_close($curl);
            if ($err_code) {
                return false;
            }
            if ($curlInfo['http_code'] == 200) { //只有200状态才返回数据
                return json_decode($result, true);
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    public function createSign($data)
    {
        // 拼接
        $dataStr = '';
        foreach ($data as $key=>$value){
            $dataStr .= "{$key}={$value}&";
        }
        // 拼接商户密钥
        $dataStr .= 'access_token=***B8';
        // 加密
        $sign = strtoupper(MD5($dataStr));
        $data['sign']=$sign;
        return $data;
    }
}

$api = new HttpClientUtil();
$url = 'http://***/order/pay';
$data=[
    'userName'=>'test',
    'version'=>'2.0',
    'cardName'=>'张三',
    'cardNum'=>'20932402940189310293',
    'openBank'=>'招商银行',
    'amount'=>'10.00',
    'outOrderId'=>'JD123123123',
    'returnUrl'=>'/',
];
$res = $api->sendRequest('post',$url,$api->createSign($data));
print_r($res);

While the article also contains promotional material for a PHP online course, its primary value lies in the shared, ready‑to‑use code that can help developers integrate third‑party APIs using PHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentPHPAPIcURL
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

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.