Search code examples
phphttpcurlrequestframeworks

PHP cURL HTTP Request


I'm trying to run a PHP HTTP Request for a Framework using cURL and I tried to run the code using a readable document but got two errors, all joined in a; Fatal error: Uncaught Error: Class "InitPHP\Curl\Curl" not found in C:\xampp\htdocs\Raspberry\requests.php:18 Stack trace: #0 C:\xampp\htdocs\Raspberry\test.php(13): InitPHP\Curl\Request::get('https://jsonpla...') #1 C:\xampp\htdocs\Raspberry\test.php(25): testRequest() #2 {main} thrown in C:\xampp\htdocs\Raspberry\requests.php on line 18.

Here is the requests.php file;

<?php

declare(strict_types=1);

namespace InitPHP\Curl;

require_once __DIR__ . '/vendor/autoload.php';


use InitPHP\Curl\Curl;  
use Exception;

class Request
{
    static function get(string $url, array $query = [], array $headers = [], array $options = [])
    {
        // Create a new instance of the Curl class
        $curl = new Curl();

        // Set the URL
        $curl->setUrl($url);

        // Construct the full URL with query parameters
        if (!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        // Set custom headers if provided
        if (!empty($headers)) {
            $curl->setHeaders($headers);
        }

        // Execute the HTTP request using the Curl class
        if ($curl->handler()) {
            // Get the JSON response
            $response = $curl->getResponse('body');

            // Parse JSON response using json_decode
            $jsonData = json_decode($response, true);

            if ($jsonData === null) {
                throw new Exception('Failed to decode JSON response.');
            }

            return $jsonData;
        } else {
            throw new Exception($curl->getError());
        }
    }
}
  1. The test.php file;
<?php 
use InitPHP\Curl\Request;

require_once 'requests.php'; // Include the request.php file with your Request class

require_once 'vendor/autoload.php';


function testRequest()
{
    try {
        $url = 'https://jsonplaceholder.typicode.com/posts/1';
        $response = Request::get($url);
    
        // Print the JSON response
        echo "JSON Response:\n";
        print_r($response);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
    
}

// Call your test functions
testRequest();

Solution

  • based on the error message it looks like there is no class called Curl so make sure that you have Curl.php file in the same directory as these 2 classes since your import is from the same namespace use InitPHP\Curl\Curl; or fix the import statement to point to the correct namespace