karewan / knhttp
Simple HTTP Client for PHP 8.3+ using curl
1.1.7
2026-03-28 19:47 UTC
Requires
- php: >=8.3
- ext-curl: *
README
Simple HTTP Client for PHP 8.3+ using curl
Installation
Requirements
PHP 8.3+
Getting started
$ composer require karewan/knhttp
Usage
GET request
/** @var KnResponse */ $res = (new KnRequest()) ->get("https://jsonplaceholder.typicode.com/todos/1") ->execForJson();
POST request
/** @var KnResponse */ $res = (new KnRequest()) ->post("https://jsonplaceholder.typicode.com/posts") ->setJsonBody([ 'title' => 'foo', 'body' => 'bar', 'userId' => 1 ]) ->execForJson();
PUT request
/** @var KnResponse */ $res = (new KnRequest()) ->put("https://jsonplaceholder.typicode.com/posts/1") ->setJsonBody([ 'title' => 'foo', 'body' => 'bar', 'userId' => 1 ]) ->execForJson();
DELETE request
/** @var KnResponse */ $res = (new KnRequest()) ->delete("https://jsonplaceholder.typicode.com/todos/1") ->execForJson();
PATCH request
/** @var KnResponse */ $res = (new KnRequest()) ->patch("https://jsonplaceholder.typicode.com/todos/1") ->execForJson();
HEAD request
/** @var KnResponse */ $res = (new KnRequest()) ->patch("https://fakerestapi.azurewebsites.net/api/v1/activities") ->execForHeaders();
OPTION request
/** @var KnResponse */ $res = (new KnRequest()) ->option("https://fakerestapi.azurewebsites.net/api/v1/activities") ->execForHeaders();
Custom method request
/** @var KnResponse */ $res = (new KnRequest()) ->request("DELETE", "https://jsonplaceholder.typicode.com/todos/1") ->execForJson();
Parallel requests execution (use setFor instead of execFor)
$req1 = (new KnRequest()) ->get("https://jsonplaceholder.typicode.com/todos/1") ->setForJson(); $req2 = (new KnRequest()) ->get("https://jsonplaceholder.typicode.com/todos/2") ->setForJson(); /** @var KnResponse[] */ $results = KnRequest::execMulti([$req1, $req2]);
KnRequest methods
// Enable verify SSL $req->setVerifySsl(true); // Check if SSL is verified $isVerifySsl = $req->isVerifySsl(); // Request timeout in seconds $req->setConnectTimeout(10); // Request connect timeout $connectTimeout = $req->getConnectTimeout(); // Set request timeout in seconds $req->setTimeout(300); // Get request timeout $timeout = $req->getTimeout(); // Set user agent $req->setUserAgent("MyApp/1.0.0"); // Get the user agent $userAgent = $req->getUserAgent(); // Set one header to the request $req->setHeader("Api-Key", "xxx"); // Remove one header to the request $req->setHeader("Api-Key", null); // Set multiple headers to the request $req->setHeaders([ "Api-Key" => "xxx", "X-Proto" => "CustomProto" ]); // Get request headers $headers = $req->getHeaders(); // Remove all added headers from the request $req->clearHeaders(); // Set a path param (https://jsonplaceholder.typicode.com/todos/{id}) $req->setPathParam("id", "1"); // Remove a path param $req->setPathParam("id", null); // Set multiple path param (https://jsonplaceholder.typicode.com/{type}/{id}) $req->setPathParams([ "type" => "todos", "id" => "1" ]); // Get the req path params $pathParams = $req->getPathParams(); // Remove all added path params from the request $req->clearPathParams(); // Set basic auth $req->setBasicAuth("username", "password"); // Get the req basic auth $basicAuth = $req->getBasicAuth(); // Remove basic auth $req->clearBasicAuth(); // Set a query param to be added to the URL $req->setQueryParam("limit", "10"); // Remove a query param $req->setQueryParam("limit", null); // Set multiple query param to be added to the URL $req->setQueryParams([ "offset" => "10", "limit" => "10" ]); // Get the req query params $queryParams = $req->getQueryParams(); // Remove all added query params from the request $req->clearQueryParams(); // Set a CURL option $req->setCurlOption(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Set multiple CURL option $req->setCurlOptions([ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2 ]); // Get the req CURL options $curlOptions = $req->getCurlOptions(); // Remove all added curl options from the request $req->clearCurlOptions(); // Set an URL encoded form body for POST and PUT $req->setFormBody([ "data1" => "xxx", "field3" => "xxx" ]); // Get the req form body $formBody = $req->getFormBody(); // Set an formData body for POST and PUT $req->setFormDataBody([ "data1" => "xxx", "field3" => "xxx" ]); // Get the req formData body $formDataBody = $req->getFormDataBody(); // Set an string body for POST and PUT $req->setStringBody("mybody"); // Get the req string body $stringBody = $req->getStringBody(); // Set an JSON body for POST and PUT $req->setJsonBody([ "jsonField1" => "xxx", "keyboard" => [ "azerty" => "bad for english", "qwerty" => "bad for french" ] ]); // Get the req JSON body $jsonBody = $req->getJsonBody(); // Set an file body for POST and PUT $req->setFileBody("myfile.txt"); // Get file body path $fileBodyPath = $req->getFileBody(); // Set an stream body for POST and PUT $req->setStreamBody($mystream); // Remove all added bodies from the request $req->clearBodies(); /** @var KnResponse */ $req->execForString(); // Set request to a string response (for execMulti) $req->setForString(); /** @var KnResponse */ $req->execForJson(); // Set request to a JSON response (for execMulti) $req->setForJson(); /** @var KnResponse */ $req->execForFile(); // Set request to a file response (for execMulti) $req->setForFile(); /** @var KnResponse */ $req->execForStream(); // Set request to a stream response (for execMulti) $req->setForStream(); // Get the raw req Url $url = $req->getUrl(); // Get the prepared URL (including query and path params) $preparedUrl = $req->getPreparedUrl(); // Get the req method $method = $req->getMethod();
KnResponse methods
/** * Returns `true` if there are no errors * @return bool */ $success = $res->isSuccessful(); /** * Returns the HTTP code (0 == error) * @return int */ $httpCode = $res->getHttpCode(); /** * Returns the response headers * @return array<string,string> */ $headers = $res->getHeaders(); /** * Returns the response data * @return mixed */ $data = $res->getData(); /** * Returns the last error code (0 == no error) * See constants KnResponse::ERROR_ * @return int */ $error = $res->getError(); /** * Returns the error label (constant name of the error) * TODO: to be replaced with an enum in a new version with breaking changes * @return string */ $errorLabel = $res->getErrorLabel(); /** * Returns the CURL error (null == no error) * @return null|string */ $curlError = $res->getCurlError(); /** * Returns the exception full stack trace (null == no exception) * @return null|string */ $exception = $res->getException(); /** * Returns the full error trace (for example => logging purposes) * @param bool $withHeaders includes headers, false by default * @param bool $withData includes data, false by default * @return string */ $fullErrorTrace = $res->getFullErrorTrace(); /** * Returns the CURL info regarding this Response * @return array */ $curlInfo = $res->getCurlInfo(); /** * Returns total time of transfer in milliseconds * @return int */ $totalTime = $res->getTotalTime();
Changelog
See the changelog here
License
See the license here
Copyright © 2025 - 2026 Florent VIALATTE (github.com/Karewan)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.