Php curl http client

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

pdeans/http

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

composer require pdeans/http

The cURL client is built on top of the Laminas Diactoros PSR-7 and PSR-17 implementations.

The client accepts an optional associative array of curl options as the first parameter to configure the cURL client. Please note that the following cURL options cannot be set in order to comply with PSR-7 standards. Instead, these options should be provided as part of the request options:

  • CURLOPT_CUSTOMREQUEST
  • CURLOPT_FOLLOWLOCATION
  • CURLOPT_HEADER
  • CURLOPT_HTTP_VERSION
  • CURLOPT_HTTPHEADER
  • CURLOPT_NOBODY
  • CURLOPT_POSTFIELDS
  • CURLOPT_RETURNTRANSFER
  • CURLOPT_URL
  • CURLOPT_USERPWD

The following is an example of how to create and configure the client:

use pdeans\Http\Client; $client = new Client(); // With options $client = new Client([ CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => true, ]);

The client comes bundled with helper methods to provide a convenient way for issuing the supported HTTP request methods.

GET , HEAD , and TRACE methods take the following parameters:

  • String representation of the target url OR a class instance that implements the PSR-7 Psr\Http\Message\UriInterface .
  • Associative array of headers [headerName => headerValue] .

POST , PUT , PATCH , OPTIONS , and DELETE methods take the two parameters listed above, plus an optional 3rd parameter for the request body:

  • String of request body data OR a class instance that implements the PSR-7 Psr\Http\Message\StreamInterface OR a resource .
// GET request with header $response = $client->get('https://example.com/1', ['custom-header' => 'header/value']); // GET request without header $response = $client->get('https://example.com/2'); // HEAD request $response = $client->head('https://example.com/2'); // TRACE request $response = $client->trace('https://example.com/2'); $headers = [ 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Basic ' . base64_encode('username:password'), ]; $data = json_encode(['json' => 'json data']); // POST request with headers and request body $response = $client->post('https://example.com/4', $headers, $data); // PUT request $response = $client->put('https://example.com/4', $headers, $data); // PATCH request $response = $client->patch('https://example.com/4', $headers, $data); // OPTIONS request $response = $client->options('https://example.com/4', $headers, $data); // DELETE request $response = $client->delete('https://example.com/4', $headers, $data);

If more control over the request is needed, the helper methods can be bypassed and the sendRequest method may be called directly. This method accepts a class instance that implements the PSR-7 Psr\Http\Message\RequestInterface .

use pdeans\Http\Factories\RequestFactory; $request = (new RequestFactory())->createRequest('GET', 'https://example.com/1'); $response = $client->sendRequest($request);

Each HTTP request returns a pdeans\Http\Response class instance, which is an implementation of the PSR-7 Psr\Http\Message\ResponseInterface .

// Issue request $response = $client->get('https://example.com/1', ['custom-header' => 'header/value']); // Response body output echo (string) $response->getBody(); // Response headers output var_dump($response->getHeaders()); var_dump($response->getHeader('custom-header')); var_dump($response->hasHeader('custom-header')); echo $response->getHeaderLine('custom-header'); // Response status code output echo $response->getStatusCode(); // Response reason phrase output echo $response->getReasonPhrase();

The following HTTP factory classes are available and each implement their associated PSR-17 factory interface:

  • pdeans\Http\Factories\RequestFactory implements Psr\Http\Message\RequestFactoryInterface
  • pdeans\Http\Factories\ResponseFactory implements Psr\Http\Message\ResponseFactoryInterface
  • pdeans\Http\Factories\ServerRequestFactory implements Psr\Http\Message\ServerRequestFactoryInterface
  • pdeans\Http\Factories\StreamFactory implements Psr\Http\Message\StreamFactoryInterface
  • pdeans\Http\Factories\UploadedFileFactory implements Psr\Http\Message\UploadedFileFactoryInterface
  • pdeans\Http\Factories\UriFactory implements Psr\Http\Message\UriFactoryInterface
use pdeans\Http\Factories\RequestFactory; use pdeans\Http\Factories\ResponseFactory; use pdeans\Http\Factories\ServerRequestFactory; use pdeans\Http\Factories\StreamFactory; use pdeans\Http\Factories\UploadedFileFactory; use pdeans\Http\Factories\UriFactory; // Psr\Http\Message\RequestFactoryInterface $requestFactory = new RequestFactory(); // Psr\Http\Message\RequestInterface $request = $requestFactory->createRequest('GET', 'https://example.com/1'); // Psr\Http\Message\ResponseFactoryInterface $responseFactory = new ResponseFactory(); // Psr\Http\Message\ResponseInterface $response = $responseFactory->createResponse(); // Psr\Http\Message\ServerRequestFactoryInterface $serverRequestFactory = new ServerRequestFactory(); // Psr\Http\Message\ServerRequestInterface $serverRequest = $serverRequestFactory->createServerRequest('GET', 'https://example.com/2'); // Psr\Http\Message\StreamFactoryInterface $streamFactory = new StreamFactory(); // Psr\Http\Message\StreamInterface $stream = $streamFactory->createStream(); $fileStream = $streamFactory->createStreamFromFile('dir/api.json'); $resourceStream = $streamFactory->createStreamFromResource(fopen('php://temp', 'r+')); // Psr\Http\Message\UploadedFileFactoryInterface $uploadedFileFactory = new UploadedFileFactory(); // Psr\Http\Message\UploadedFileInterface $uploadedFile = $uploadedFileFactory->createUploadedFile($fileStream); // Psr\Http\Message\UriFactoryInterface $uriFactory = new UriFactory(); // Psr\Http\Message\UriInterface $uri = $uriFactory->createUri();

As this library is a layer built upon existing libraries and standards, it is encouraged that you read through the documentation of these libraries and standards to get a better understanding of how the various components work.

Источник

PHP: Отправка HTTP-запросов с помощью php curl

(Client URL Library) — это библиотека для отправки HTTP-запросов и получения ответов от веб-серверов. С помощью cURL можно создавать автоматические программы, которые могут взаимодействовать с веб-сервисами и получать данные с других веб-сайтов.

Примеры использования PHP cURL:

Пример 1: Отправка GET-запроса на URL и получение ответа:

В этом примере мы отправляем GET-запрос на URL https://www.example.com/api/handler/ и получаем ответ от сервера. Функция curl_setopt_array() используется для настройки параметров запроса, включая URL-адрес, заголовки, тип запроса и другие параметры.

$url = 'https://www.example.com/api/handler/'; $curl = curl_init(); curl_setopt_array( $curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '. 'AppleWebKit/537.36 (KHTML, like Gecko) '. 'Chrome/58.0.3029.110 Safari/537.36' ]); $response = curl_exec( $curl ); curl_close( $curl ); echo $response;

Пример 2: Отправка POST-запроса на URL и получение ответа:

В этом примере мы отправляем POST-запрос на URL https://www.example.com/api/handler/, передавая параметры username и password. Функция curl_setopt_array() используется для настройки параметров запроса, включая URL-адрес, заголовки, тип запроса и другие параметры.

$url = 'https://www.example.com/api/handler/'; $data = [ 'username' => 'admin', 'password' => 'secret' ]; $curl = curl_init(); curl_setopt_array( $curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $data, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '. 'AppleWebKit/537.36 (KHTML, like Gecko) '. 'Chrome/58.0.3029.110 Safari/537.36' ]); $response = curl_exec( $curl ); curl_close( $curl ); echo $response;

Пример 3: Загрузка файла на сервер с помощью POST-запроса:

В этом примере мы загружаем файл file.jpg на сервер с помощью POST-запроса на URL https://www.example.com/upload.php. Мы используем функцию CURLFile() для передачи файла в запросе.

$url = 'https://www.example.com/upload.php'; $file_path = '/path/to/file.jpg'; $curl = curl_init(); curl_setopt_array( $curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => [ 'file' => new CURLFile( $file_path ) ], CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '. 'AppleWebKit/537.36 (KHTML, like Gecko) '. 'Chrome/58.0.3029.110 Safari/537.36' ]); $response = curl_exec( $curl ); curl_close( $curl ); echo $response;

Пример 4: Установка пользовательских заголовков и настройка соединения:

В этом примере мы устанавливаем пользовательские заголовки Authorization и Content-Type, а также настраиваем соединение с помощью параметров CURLOPT_CONNECTTIMEOUT и CURLOPT_TIMEOUT. Функция curl_setopt_array() используется для настройки параметров запроса, включая URL-адрес, заголовки, тип запроса и другие параметры.

$url = 'https://www.example.com/api/handler/'; $header = [ 'Authorization: Bearer ', 'Content-Type: application/json' ]; $curl = curl_init(); curl_setopt_array( $curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $header, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 30, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '. 'AppleWebKit/537.36 (KHTML, like Gecko) '. 'Chrome/58.0.3029.110 Safari/537.36' ]); $response = curl_exec( $curl ); curl_close( $curl ); echo $response;

Пример 5: Использование прокси-сервера:

В этом примере мы используем прокси-сервер http://proxy.example.com:8080 для отправки запроса. Мы также передаем имя пользователя и пароль для аутентификации на прокси-сервере с помощью параметра CURLOPT_PROXYUSERPWD. Функция curl_setopt_array() используется для настройки параметров запроса, включая URL-адрес, заголовки, тип запроса и другие параметры.

$url = 'https://www.example.com/api/handler/'; $proxy = 'http://proxy.example.com:8080'; $curl = curl_init(); curl_setopt_array( $curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_PROXY => $proxy, CURLOPT_PROXYUSERPWD => '<username>:<password>', CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '. 'AppleWebKit/537.36 (KHTML, like Gecko) '. 'Chrome/58.0.3029.110 Safari/537.36' ]); $response = curl_exec( $curl ); curl_close( $curl ); echo $response;

Источник

Читайте также:  Двойные квадратные скобки javascript
Оцените статью