Kotchasan Framework Documentation

Kotchasan Framework Documentation

Curl Class - HTTP Request Handler

EN 05 Feb 2026 07:47

Curl Class - HTTP Request Handler

The Curl class is a tool for sending HTTP requests using cURL in the Kotchasan Framework.

namespace

Kotchasan\Curl;

Features

The Curl class supports various HTTP request formats including authentication, proxy settings, and header management.

Key Properties

protected $error = 0;           // cURL error code (0 = no error)
protected $errorMessage = '';   // cURL error message
protected $headers = [];        // HTTP headers
protected $options = [];        // CURLOPT parameters;

Main Methods

__construct()

Creates a Curl instance with default settings

class ExampleClass {
    <?php
public function __construct();
}

Throws: Exception if cURL is not supported

Usage Examples:

use Kotchasan\Curl;

// Create Curl instance
$curl = new Curl();

// Example of checking cURL support
try {
    $curl = new Curl();
    echo "cURL is available";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

get()

Send GET request

class ExampleClass {
    <?php
public function get($url, $params = []): string;
}

Parameters:

  • $url - Target URL
  • $params - Parameters (array or string)

Returns: Response body

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Simple GET
$response = $curl->get('https://api.example.com/users');
echo $response;

// GET with parameters
$params = [
    'page' => 1,
    'limit' => 10,
    'search' => 'john'
];
$response = $curl->get('https://api.example.com/users', $params);

// Error checking
if ($curl->error()) {
    echo 'Error occurred: ' . $curl->errorMessage();
} else {
    echo 'Success: ' . $response;
}

// API data fetching system
function fetchApiData($endpoint, $params = []) {
    $curl = new Curl();
    $response = $curl->get("https://api.myservice.com/{$endpoint}", $params);

    if ($curl->error()) {
        return [
            'success' => false,
            'error' => $curl->errorMessage()
        ];
    }

    return [
        'success' => true,
        'data' => json_decode($response, true)
    ];
}

// Usage
$result = fetchApiData('users', ['status' => 'active']);
if ($result['success']) {
    foreach ($result['data'] as $user) {
        echo "User: {$user['name']}\n";
    }
}

post()

Send POST request

class ExampleClass {
    <?php
public function post($url, $params = []): string;
}

Parameters:

  • $url - Target URL
  • $params - Data to send (array or string)

Returns: Response body

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// POST array data
$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'age' => 30
];
$response = $curl->post('https://api.example.com/users', $data);

// POST JSON data
$curl->setHeaders(['Content-Type' => 'application/json']);
$jsonData = json_encode($data);
$response = $curl->post('https://api.example.com/users', $jsonData);

// POST form data
$formData = [
    'username' => 'johndoe',
    'password' => 'secret123',
    'remember_me' => '1'
];
$response = $curl->post('https://api.example.com/login', $formData);

// API data sending system
function sendDataToApi($endpoint, $data) {
    $curl = new Curl();
    $curl->setHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . API_TOKEN
    ]);

    $response = $curl->post("https://api.myservice.com/{$endpoint}", json_encode($data));

    if ($curl->error()) {
        return [
            'success' => false,
            'error' => $curl->errorMessage()
        ];
    }

    $result = json_decode($response, true);
    return [
        'success' => true,
        'data' => $result
    ];
}

// Create new user
$newUser = [
    'name' => 'Jane Smith',
    'email' => 'jane@example.com',
    'role' => 'user'
];

$result = sendDataToApi('users', $newUser);
if ($result['success']) {
    echo "User created successfully ID: " . $result['data']['id'];
}

put()

Send PUT request

class ExampleClass {
    <?php
public function put($url, $params = []): string;
}

Parameters:

  • $url - Target URL
  • $params - Data to send

Returns: Response body

delete()

Send DELETE request

class ExampleClass {
    <?php
public function delete($url, $params): string;
}

Parameters:

  • $url - Target URL
  • $params - Data to send

Returns: Response body

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Update data with PUT
$updateData = [
    'name' => 'John Updated',
    'email' => 'john.updated@example.com'
];
$response = $curl->put('https://api.example.com/users/123', $updateData);

// Delete data with DELETE
$response = $curl->delete('https://api.example.com/users/123', []);

// CRUD API system
class ApiClient {
    private $curl;
    private $baseUrl;
    private $token;

    public function __construct($baseUrl, $token = null) {
        $this->curl = new Curl();
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->token = $token;

        if ($token) {
            $this->curl->setHeaders([
                'Authorization' => 'Bearer ' . $token,
                'Content-Type' => 'application/json'
            ]);
        }
    }

    public function create($endpoint, $data) {
        $url = $this->baseUrl . '/' . ltrim($endpoint, '/');
        $response = $this->curl->post($url, json_encode($data));
        return $this->handleResponse($response);
    }

    public function read($endpoint, $params = []) {
        $url = $this->baseUrl . '/' . ltrim($endpoint, '/');
        $response = $this->curl->get($url, $params);
        return $this->handleResponse($response);
    }

    public function update($endpoint, $data) {
        $url = $this->baseUrl . '/' . ltrim($endpoint, '/');
        $response = $this->curl->put($url, json_encode($data));
        return $this->handleResponse($response);
    }

    public function delete($endpoint) {
        $url = $this->baseUrl . '/' . ltrim($endpoint, '/');
        $response = $this->curl->delete($url, '');
        return $this->handleResponse($response);
    }

    private function handleResponse($response) {
        if ($this->curl->error()) {
            return [
                'success' => false,
                'error' => $this->curl->errorMessage()
            ];
        }

        return [
            'success' => true,
            'data' => json_decode($response, true)
        ];
    }
}

// ApiClient usage
$api = new ApiClient('https://api.example.com', 'your-api-token');

// Create user
$result = $api->create('users', ['name' => 'John', 'email' => 'john@example.com']);

// Read user
$result = $api->read('users/123');

// Update user
$result = $api->update('users/123', ['name' => 'John Updated']);

// Delete user
$result = $api->delete('users/123');

Send HEAD request

class ExampleClass {
    <?php
public function head($url, $params = []): string;
}

Parameters:

  • $url - Target URL
  • $params - Parameters

Returns: Response headers

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Check headers only
$response = $curl->head('https://api.example.com/users/123');

// Use HEAD to check file existence
function checkFileExists($url) {
    $curl = new Curl();
    $curl->head($url);

    return $curl->error() === 0;
}

if (checkFileExists('https://example.com/image.jpg')) {
    echo "File exists";
} else {
    echo "File not found";
}

setHeaders()

Set HTTP headers

class ExampleClass {
    <?php
public function setHeaders($headers): $this;
}

Parameters:

  • $headers - Headers array

Returns: $this for method chaining

setOptions()

Set cURL options

class ExampleClass {
    <?php
public function setOptions($options): $this;
}

Parameters:

  • $options - Options array

Returns: $this for method chaining

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Set headers
$curl->setHeaders([
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer token123',
    'User-Agent' => 'MyApp/1.0',
    'Accept' => 'application/json'
]);

// Set cURL options
$curl->setOptions([
    CURLOPT_TIMEOUT => 60,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 5,
    CURLOPT_SSL_VERIFYPEER => false
]);

// Method chaining
$response = $curl
    ->setHeaders(['Content-Type' => 'application/json'])
    ->setOptions([CURLOPT_TIMEOUT => 30])
    ->get('https://api.example.com/data');

httpauth()

Set HTTP authentication

class ExampleClass {
    <?php
public function httpauth($username = '', $password = '', $type = 'any'): $this;
}

Parameters:

  • $username - Username
  • $password - Password
  • $type - Authentication type (any, digest, basic, etc.)

Returns: $this for method chaining

httpproxy()

Use PROXY

class ExampleClass {
    <?php
public function httpproxy($url = '', $port = 80, $username = null, $password = null): $this;
}

Parameters:

  • $url - Proxy URL
  • $port - Port
  • $username - Proxy username (optional)
  • $password - Proxy password (optional)

Returns: $this for method chaining

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Use Basic Authentication
$response = $curl
    ->httpauth('username', 'password', 'basic')
    ->get('https://api.example.com/secure-data');

// Use Proxy
$response = $curl
    ->httpproxy('proxy.example.com', 8080, 'proxy_user', 'proxy_pass')
    ->get('https://api.example.com/data');

// Secure API access system
class SecureApiClient {
    private $curl;

    public function __construct($username, $password) {
        $this->curl = new Curl();
        $this->curl->httpauth($username, $password, 'basic');
    }

    public function getData($endpoint) {
        $response = $this->curl->get("https://secure-api.example.com/{$endpoint}");

        if ($this->curl->error()) {
            return null;
        }

        return json_decode($response, true);
    }
}

$secureApi = new SecureApiClient('api_user', 'api_password');
$data = $secureApi->getData('sensitive-data');

referer()

Set referer

class ExampleClass {
    <?php
public function referer($referrer): $this;
}

Parameters:

  • $referrer - Referer URL

Returns: $this for method chaining

setCookie()

Set cookie file

class ExampleClass {
    <?php
public function setCookie($cookiePath): $this;
}

Parameters:

  • $cookiePath - Cookie file path

Returns: $this for method chaining

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();

// Set referer
$curl->referer('https://example.com/previous-page');

// Use cookie file
$cookieFile = ROOT_PATH . 'tmp/cookies.txt';
$curl->setCookie($cookieFile);

// Login and keep session system
function loginAndKeepSession($username, $password) {
    $curl = new Curl();
    $cookieFile = ROOT_PATH . 'tmp/session_cookies.txt';

    // Set cookie file
    $curl->setCookie($cookieFile);

    // Send login data
    $loginData = [
        'username' => $username,
        'password' => $password
    ];

    $response = $curl->post('https://example.com/login', $loginData);

    if ($curl->error()) {
        return false;
    }

    // Check successful login
    if (strpos($response, 'welcome') !== false) {
        return $cookieFile; // Return cookie file path
    }

    return false;
}

// Access protected page
function accessProtectedPage($cookieFile, $url) {
    $curl = new Curl();
    $curl->setCookie($cookieFile);

    return $curl->get($url);
}

// Usage
$cookieFile = loginAndKeepSession('myuser', 'mypass');
if ($cookieFile) {
    $protectedContent = accessProtectedPage($cookieFile, 'https://example.com/dashboard');
    echo $protectedContent;
}

error()

Check cURL error code

class ExampleClass {
    <?php
public function error(): int;
}

Returns: Error code (0 = no error)

errorMessage()

Get cURL error message

class ExampleClass {
    <?php
public function errorMessage(): string;
}

Returns: Error message

Usage Examples:

use Kotchasan\Curl;

$curl = new Curl();
$response = $curl->get('https://invalid-url.example.com');

if ($curl->error()) {
    echo "Error code: " . $curl->error() . "\n";
    echo "Message: " . $curl->errorMessage() . "\n";
} else {
    echo "Success: " . $response;
}

// Detailed error handling system
function handleCurlError($curl) {
    $errorCode = $curl->error();
    $errorMessage = $curl->errorMessage();

    $errorTypes = [
        CURLE_COULDNT_CONNECT => 'Could not connect',
        CURLE_OPERATION_TIMEOUTED => 'Connection timeout',
        CURLE_COULDNT_RESOLVE_HOST => 'Host not found',
        CURLE_SSL_CONNECT_ERROR => 'SSL error',
        CURLE_HTTP_NOT_FOUND => 'Page not found (404)'
    ];

    $friendlyMessage = $errorTypes[$errorCode] ?? 'Unknown error';

    return [
        'code' => $errorCode,
        'message' => $errorMessage,
        'friendly' => $friendlyMessage
    ];
}

Advanced Usage Examples

use Kotchasan\Curl;

// Complete HTTP Client system
class HttpClient {
    private $curl;
    private $baseUrl;
    private $defaultHeaders;
    private $timeout;

$timeout = 3; // 0) {
        $this->curl = new Curl();
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;
        $this->defaultHeaders = [
            'User-Agent' => 'HttpClient/1.0',
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ];

        $this->curl->setOptions([
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3
        ]);
    }

    public function setAuth($username, $password, $type = 'basic') {
        $this->curl->httpauth($username, $password, $type);
        return $this;
    }

    public function setHeaders($headers) {
        $this->defaultHeaders = array_merge($this->defaultHeaders, $headers);
        return $this;
    }

    public function get($endpoint, $params = []) {
        return $this->request('GET', $endpoint, $params);
    }

    public function post($endpoint, $data = []) {
        return $this->request('POST', $endpoint, $data);
    }

    public function put($endpoint, $data = []) {
        return $this->request('PUT', $endpoint, $data);
    }

    public function delete($endpoint) {
        return $this->request('DELETE', $endpoint);
    }

    private function request($method, $endpoint, $data = []) {
        $url = $this->baseUrl . '/' . ltrim($endpoint, '/');

        $this->curl->setHeaders($this->defaultHeaders);

        $startTime = microtime(true);

        switch (strtoupper($method)) {
            case 'GET':
                $response = $this->curl->get($url, $data);
                break;
            case 'POST':
                $response = $this->curl->post($url, is_array($data) ? json_encode($data) : $data);
                break;
            case 'PUT':
                $response = $this->curl->put($url, is_array($data) ? json_encode($data) : $data);
                break;
            case 'DELETE':
                $response = $this->curl->delete($url, '');
                break;
            default:
                throw new \InvalidArgumentException("Unsupported HTTP method: {$method}");
        }

        $endTime = microtime(true);
        $responseTime = round(($endTime - $startTime) * 1000, 2);

        return [
            'success' => !$this->curl->error(),
            'status_code' => $this->curl->error(),
            'error_message' => $this->curl->errorMessage(),
            'response' => $response,
            'response_time' => $responseTime . 'ms',
            'url' => $url,
            'method' => $method
        ];
    }
}

// API Gateway system
class ApiGateway {
    private $clients = [];

    public function addService($name, $baseUrl, $config = []) {
        $client = new HttpClient($baseUrl, $config['timeout'] ?? 30);

        if (isset($config['auth'])) {
            $client->setAuth($config['auth']['username'], $config['auth']['password']);
        }

        if (isset($config['headers'])) {
            $client->setHeaders($config['headers']);
        }

        $this->clients[$name] = $client;
        return $this;
    }

    public function call($service, $method, $endpoint, $data = []) {
        if (!isset($this->clients[$service])) {
            throw new \InvalidArgumentException("Service '{$service}' not found");
        }

        $client = $this->clients[$service];

        switch (strtolower($method)) {
            case 'get':
                return $client->get($endpoint, $data);
            case 'post':
                return $client->post($endpoint, $data);
            case 'put':
                return $client->put($endpoint, $data);
            case 'delete':
                return $client->delete($endpoint);
            default:
                throw new \InvalidArgumentException("Unsupported method: {$method}");
        }
    }
}

// API Gateway usage
$gateway = new ApiGateway();

// Add services
$gateway->addService('users', 'https://user-api.example.com', [
    'timeout' => 30,
    'auth' => ['username' => 'api_user', 'password' => 'api_pass'],
    'headers' => ['X-API-Version' => 'v1']
]);

$gateway->addService('orders', 'https://order-api.example.com', [
    'timeout' => 60,
    'headers' => ['Authorization' => 'Bearer ' . ORDER_API_TOKEN]
]);

$gateway->addService('payments', 'https://payment-api.example.com', [
    'timeout' => 45,
    'headers' => ['X-API-Key' => PAYMENT_API_KEY]
]);

// Call services
$userResult = $gateway->call('users', 'get', 'users/123');
$orderResult = $gateway->call('orders', 'post', 'orders', [
    'user_id' => 123,
    'items' => [['product_id' => 1, 'quantity' => 2]]
]);

// Webhook Handler system
class WebhookHandler {
    private $curl;

    public function __construct() {
        $this->curl = new Curl();
        $this->curl->setOptions([
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
    }

    public function sendWebhook($url, $data, $secret = null) {
        $payload = json_encode($data);

        $headers = ['Content-Type' => 'application/json'];

        if ($secret) {
            $signature = hash_hmac('sha256', $payload, $secret);
            $headers['X-Hub-Signature-256'] = 'sha256=' . $signature;
        }

        $this->curl->setHeaders($headers);

        $response = $this->curl->post($url, $payload);

        return [
            'success' => !$this->curl->error(),
            'error' => $this->curl->errorMessage(),
            'response' => $response
        ];
    }

    public function broadcast($urls, $data, $secret = null) {
        $results = [];

        foreach ($urls as $url) {
            $results[$url] = $this->sendWebhook($url, $data, $secret);
        }

        return $results;
    }
}

// Webhook usage
$webhook = new WebhookHandler();

$eventData = [
    'event' => 'user.created',
    'data' => [
        'user_id' => 123,
        'email' => 'user@example.com',
        'created_at' => date('c')
    ]
];

$webhookUrls = [
    'https://service1.example.com/webhook',
    'https://service2.example.com/webhook',
    'https://service3.example.com/webhook'
];

$results = $webhook->broadcast($webhookUrls, $eventData, 'webhook_secret_key');

foreach ($results as $url => $result) {
    if ($result['success']) {
        echo "Webhook sent to {$url}: SUCCESS\n";
    } else {
        echo "Webhook failed for {$url}: {$result['error']}\n";
    }
}

Usage Notes

  1. Requirements: cURL extension must be available in the system
  2. Security: Supports SSL/TLS and authentication
  3. Performance: Configurable timeout and redirect limits
  4. Error handling: Use error() and errorMessage() to check for errors
  5. Headers: Custom headers can be configured

The Curl class is a powerful tool for HTTP requests in the Kotchasan Framework, supporting efficient connections to APIs and external services.