PHP

Класс для работы с CURL на PHP

Создадим универсальный класс для HTTP запросов GET/POST/PUT на основе CURL.

(пока еще не по PSR-7)

Сам класс:

/**
 * Перенаправляем запросы
 * Class Proxy
 * @package App\Helpers
 */
class Proxy
{
    public static function request($url, $method, $body = [])
    {
        $method = strtoupper($method);

        $headers = request()->headers->all()

        return Proxy::curl($url, $method, $body, $headers);
    }

    private static function curl($url, $method, $bodyFields = [], $headers = [])
    {
        function prepareHeaders($headers)
        {
            $flattened = [];
            foreach ($headers as $key => $header) {
                if (is_int($key)) {
                    $flattened[] = $header;
                } else {
                    $flattened[] = $key . ': ' . $header;
                }
            }
            return $flattened;//implode("\r\n", $flattened);
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => prepareHeaders($headers),
            CURLOPT_POSTFIELDS => is_array($bodyFields) ? json_encode($bodyFields, JSON_UNESCAPED_UNICODE) : $bodyFields,
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }
}

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

$proxy = Settings::get($name, 'service_proxy');

if ($proxy) {
  $url = $proxy;
  $msg = Proxy::request($url, 'POST', json_decode($request->getContent(), 1));
  return response($msg)->header('Content-Type', 'application/json');
}

Leave a reply