[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-ru-http-proksi-php-guzzle-laravel":3},{"success":4,"payload":5,"related":70,"errors":165},true,{"id":6,"slug":7,"title":8,"excerpt":9,"body_html":10,"meta_title":11,"meta_description":12,"canonical_url":13,"canonical_override":14,"og_title":15,"og_description":16,"og_image_url":17,"faq_json":18,"key_takeaways":34,"allow_index":4,"noindex_google_only":40,"allow_follow":4,"published_at":41,"updated_at":41,"content_updated_at":42,"featured_image_url":17,"featured_image_alt":14,"card_image_url":14,"reading_time_minutes":43,"author":44,"categories":48,"tags":55,"alternates":56,"locale_paths":58,"views":69},61,"http-proksi-php-guzzle-laravel","Полное руководство по использованию HTTP-прокси в PHP: cURL, Guzzle, Symfony и Laravel","Практическое руководство для PHP-разработчиков по работе с HTTP-прокси. Разбираем нативный cURL, Guzzle, Symfony HTTP Client, интеграцию с Laravel и асинхронные запросы — с готовыми примерами кода.","\u003Cp>Если вы занимаетесь скрейпингом, интеграцией с внешними API или автоматизацией в PHP — рано или поздно столкнётесь с блокировками по IP. Провайдеры ограничивают количество запросов, CDN вроде Cloudflare возвращают 403, а популярные сайты требуют обхода rate limit. \u003Cstrong>PHP proxy\u003C\u002Fstrong> — это не просто настройка CURLOPT_PROXY, а целый стек решений: ротация IP, обработка ошибок, управление сессиями и TLS-конфигурация.\u003C\u002Fp>\n\n\u003Cp>В этом руководстве мы пройдём путь от базового cURL до production-ready решения на Laravel: сервис-класс с пулом \u003Ca href=\"\u002Fru\u002Fproxy\u002Fresidential\">residential-прокси\u003C\u002Fa>, очередями и повторными попытками. Все примеры используют ProxyHat — провайдера residential и mobile прокси.\u003C\u002Fp>\n\n\u003Ch2>Базовая настройка: нативный cURL с CURLOPT_PROXY\u003C\u002Fh2>\n\n\u003Cp>cURL — стандарт де-факто для HTTP-запросов в PHP. Для работы через прокси используются опции \u003Ccode>CURLOPT_PROXY\u003C\u002Fcode> (адрес прокси-сервера) и \u003Ccode>CURLOPT_PROXYUSERPWD\u003C\u002Fcode> (авторизация). Рассмотрим полный пример с обработкой ошибок и таймаутами.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nclass CurlProxyClient\n{\n    private string $proxyHost = &apos;gate.proxyhat.com&apos;;\n    private int $proxyPort = 8080;\n    private string $username;\n    private string $password;\n\n    public function __construct(string $username, string $password)\n    {\n        $this-&gt;username = $username;\n        $this-&gt;password = $password;\n    }\n\n    \u002F**\n     * Выполняет HTTP-запрос через прокси с ротацией IP\n     * \n     * @param string $url Целевой URL\n     * @param string $country Код страны для геотаргетинга (опционально)\n     * @param string $session Идентификатор сессии для sticky IP (опционально)\n     * @return array [&apos;status&apos; =&gt; int, &apos;body&apos; =&gt; string, &apos;headers&apos; =&gt; array]\n     * @throws RuntimeException\n     *\u002F\n    public function get(\n        string $url,\n        ?string $country = null,\n        ?string $session = null\n    ): array {\n        $ch = curl_init();\n        \n        \u002F\u002F Формируем имя пользователя с флагами геотаргетинга и сессии\n        $proxyUser = $this-&gt;buildProxyUsername($country, $session);\n        \n        \u002F\u002F Базовые опции cURL\n        curl_setopt_array($ch, [\n            CURLOPT_URL =&gt; $url,\n            CURLOPT_RETURNTRANSFER =&gt; true,\n            CURLOPT_FOLLOWLOCATION =&gt; true,\n            CURLOPT_MAXREDIRS =&gt; 5,\n            CURLOPT_TIMEOUT =&gt; 30,\n            CURLOPT_CONNECTTIMEOUT =&gt; 10,\n            \n            \u002F\u002F Настройка прокси\n            CURLOPT_PROXY =&gt; $this-&gt;proxyHost,\n            CURLOPT_PROXYPORT =&gt; $this-&gt;proxyPort,\n            CURLOPT_PROXYUSERPWD =&gt; &quot;{$proxyUser}:{$this-&gt;password}&quot;,\n            CURLOPT_PROXYTYPE =&gt; CURLPROXY_HTTP,\n            \n            \u002F\u002F SSL\u002FTLS конфигурация\n            CURLOPT_SSL_VERIFYPEER =&gt; true,\n            CURLOPT_SSL_VERIFYHOST =&gt; 2,\n            CURLOPT_CAINFO =&gt; $this-&gt;getCaBundlePath(),\n            \n            \u002F\u002F Заголовки\n            CURLOPT_USERAGENT =&gt; &apos;Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36&apos;,\n            CURLOPT_HTTPHEADER =&gt; [\n                &apos;Accept: text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8&apos;,\n                &apos;Accept-Language: en-US,en;q=0.9&apos;,\n            ],\n            \n            \u002F\u002F Захват заголовков ответа\n            CURLOPT_HEADER =&gt; true,\n        ]);\n        \n        $response = curl_exec($ch);\n        $error = curl_error($ch);\n        $errno = curl_errno($ch);\n        $info = curl_getinfo($ch);\n        \n        curl_close($ch);\n        \n        if ($errno !== CURLE_OK) {\n            throw new RuntimeException(\n                &quot;cURL error [{$errno}]: {$error}&quot;,\n                $errno\n            );\n        }\n        \n        \u002F\u002F Разделяем заголовки и тело\n        $headerSize = $info[&apos;header_size&apos;];\n        $headers = substr($response, 0, $headerSize);\n        $body = substr($response, $headerSize);\n        \n        return [\n            &apos;status&apos; =&gt; $info[&apos;http_code&apos;],\n            &apos;body&apos; =&gt; $body,\n            &apos;headers&apos; =&gt; $this-&gt;parseHeaders($headers),\n            &apos;effective_url&apos; =&gt; $info[&apos;url&apos;],\n            &apos;total_time&apos; =&gt; $info[&apos;total_time&apos;],\n        ];\n    }\n    \n    \u002F**\n     * Строит имя пользователя с флагами ProxyHat\n     *\u002F\n    private function buildProxyUsername(?string $country, ?string $session): string\n    {\n        $parts = [$this-&gt;username];\n        \n        if ($country !== null) {\n            $parts[] = &quot;country-{$country}&quot;;\n        }\n        \n        if ($session !== null) {\n            $parts[] = &quot;sid-{$session}&quot;;\n        }\n        \n        return implode(&apos;-&apos;, $parts);\n    }\n    \n    \u002F**\n     * Возвращает путь к CA-бандлу\n     *\u002F\n    private function getCaBundlePath(): string\n    {\n        \u002F\u002F Приоритет: системный бандл &gt; bundled с cURL &gt; локальный файл\n        $candidates = [\n            &apos;\u002Fetc\u002Fssl\u002Fcerts\u002Fca-certificates.crt&apos;, \u002F\u002F Debian\u002FUbuntu\n            &apos;\u002Fetc\u002Fpki\u002Ftls\u002Fcerts\u002Fca-bundle.crt&apos;,   \u002F\u002F RHEL\u002FCentOS\n            &apos;\u002Fusr\u002Flocal\u002Fshare\u002Fcerts\u002Fca-root-nss.crt&apos;, \u002F\u002F FreeBSD\n            __DIR__ . &apos;\u002Fcacert.pem&apos;, \u002F\u002F Локальный fallback\n        ];\n        \n        foreach ($candidates as $path) {\n            if (file_exists($path)) {\n                return $path;\n            }\n        }\n        \n        \u002F\u002F Если ничего не найдено, отключаем верификацию (только для dev!)\n        return &apos;&apos;;\n    }\n    \n    \u002F**\n     * Парсит заголовки ответа в массив\n     *\u002F\n    private function parseHeaders(string $headerText): array\n    {\n        $headers = [];\n        $lines = explode(&quot;\\r\\n&quot;, trim($headerText));\n        \n        foreach ($lines as $line) {\n            if (strpos($line, &apos;:&apos;) !== false) {\n                [$key, $value] = explode(&apos;:&apos;, $line, 2);\n                $headers[trim($key)] = trim($value);\n            }\n        }\n        \n        return $headers;\n    }\n}\n\n\u002F\u002F Использование:\ntry {\n    $client = new CurlProxyClient(&apos;user&apos;, &apos;your_password&apos;);\n    \n    \u002F\u002F Запрос с ротацией IP (новый IP для каждого запроса)\n    $result = $client-&gt;get(&apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;);\n    echo &quot;IP: &quot; . json_decode($result[&apos;body&apos;], true)[&apos;origin&apos;] . &quot;\\n&quot;;\n    \n    \u002F\u002F Запрос с геотаргетингом (США)\n    $result = $client-&gt;get(&apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;US&apos;);\n    \n    \u002F\u002F Sticky-сессия (тот же IP на протяжении сессии)\n    $sessionId = bin2hex(random_bytes(8));\n    $result = $client-&gt;get(&apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, null, $sessionId);\n    \n} catch (RuntimeException $e) {\n    echo &quot;Ошибка: &quot; . $e-&gt;getMessage() . &quot;\\n&quot;;\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>Ключевые моменты в этом примере:\u003C\u002Fp>\n\u003Cul>\n\u003Cli>\u003Cstrong>CURLOPT_PROXYUSERPWD\u003C\u002Fstrong> — авторизация в формате \u003Ccode>username:password\u003C\u002Fcode>\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Геотаргетинг\u003C\u002Fstrong> — добавляем \u003Ccode>country-US\u003C\u002Fcode> к имени пользователя\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Sticky-сессии\u003C\u002Fstrong> — идентификатор \u003Ccode>sid-abc123\u003C\u002Fcode> гарантирует тот же IP\u003C\u002Fli>\n\u003Cli>\u003Cstrong>TLS-верификация\u003C\u002Fstrong> — указываем путь к CA-бандлу\u003C\u002Fli>\n\u003C\u002Ful>\n\n\u003Ch2>Guzzle HTTP Client: современный подход к Guzzle proxy\u003C\u002Fh2>\n\n\u003Cp>Guzzle — самая популярная HTTP-библиотека для PHP с PSR-7 совместимостью. Настройка прокси в Guzzle делается через опцию \u003Ccode>proxy\u003C\u002Fcode> в массиве конфигурации клиента или отдельного запроса.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nrequire &apos;vendor\u002Fautoload.php&apos;;\n\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Exception\\RequestException;\nuse GuzzleHttp\\HandlerStack;\nuse GuzzleHttp\\Middleware;\nuse Psr\\Http\\Message\\RequestInterface;\nuse Psr\\Http\\Message\\ResponseInterface;\n\nclass GuzzleProxyClient\n{\n    private Client $client;\n    private string $username;\n    private string $password;\n    private string $proxyHost = &apos;gate.proxyhat.com&apos;;\n    private int $proxyPort = 8080;\n    \n    \u002F\u002F Пул стран для ротации\n    private array $countries = [&apos;US&apos;, &apos;DE&apos;, &apos;GB&apos;, &apos;FR&apos;, &apos;JP&apos;];\n    \n    public function __construct(string $username, string $password, array $config = [])\n    {\n        $this-&gt;username = $username;\n        $this-&gt;password = $password;\n        \n        $this-&gt;client = $this-&gt;createClient($config);\n    }\n    \n    \u002F**\n     * Создаёт Guzzle-клиент с middleware для retry и логирования\n     *\u002F\n    private function createClient(array $config = []): Client\n    {\n        $handlerStack = HandlerStack::create();\n        \n        \u002F\u002F Middleware для повторных попыток\n        $handlerStack-&gt;push(Middleware::retry(\n            function ($retries, RequestInterface $request, ResponseInterface $response = null, $exception = null) {\n                \u002F\u002F Повторяем до 3 раз\n                if ($retries &gt;= 3) {\n                    return false;\n                }\n                \n                \u002F\u002F Повторяем при 429, 500, 502, 503, 504\n                if ($response &amp;&amp; in_array($response-&gt;getStatusCode(), [429, 500, 502, 503, 504])) {\n                    return true;\n                }\n                \n                \u002F\u002F Повторяем при сетевых ошибках\n                if ($exception instanceof \\GuzzleHttp\\Exception\\ConnectException) {\n                    return true;\n                }\n                \n                return false;\n            },\n            function ($retries) {\n                \u002F\u002F Экспоненциальная задержка: 1s, 2s, 4s\n                return 1000 * (2 ** ($retries - 1));\n            }\n        ));\n        \n        \u002F\u002F Middleware для логирования\n        $handlerStack-&gt;push(Middleware::tap(\n            function (RequestInterface $request, array $options) {\n                echo sprintf(\n                    &quot;[%s] %s %s\\n&quot;,\n                    date(&apos;Y-m-d H:i:s&apos;),\n                    $request-&gt;getMethod(),\n                    $request-&gt;getUri()\n                );\n            }\n        ));\n        \n        $defaultConfig = [\n            &apos;handler&apos; =&gt; $handlerStack,\n            &apos;timeout&apos; =&gt; 30,\n            &apos;connect_timeout&apos; =&gt; 10,\n            &apos;verify&apos; =&gt; true,\n            &apos;headers&apos; =&gt; [\n                &apos;User-Agent&apos; =&gt; &apos;Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36&apos;,\n                &apos;Accept&apos; =&gt; &apos;text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8&apos;,\n            ],\n        ];\n        \n        return new Client(array_merge($defaultConfig, $config));\n    }\n    \n    \u002F**\n     * Выполняет запрос с автоматической ротацией IP\n     * \n     * @param string $method HTTP-метод\n     * @param string $url Целевой URL\n     * @param array $options Дополнительные опции Guzzle\n     * @param array $proxyOptions Опции прокси: country, session, rotate\n     * @return ResponseInterface\n     *\u002F\n    public function request(\n        string $method,\n        string $url,\n        array $options = [],\n        array $proxyOptions = []\n    ): ResponseInterface {\n        \u002F\u002F Формируем конфигурацию прокси\n        $proxyConfig = $this-&gt;buildProxyConfig($proxyOptions);\n        \n        \u002F\u002F Объединяем с опциями запроса\n        $options[&apos;proxy&apos;] = $proxyConfig[&apos;url&apos;];\n        \n        \u002F\u002F Добавляем кастомные заголовки для отладки\n        $options[&apos;headers&apos;][&apos;X-Proxy-Country&apos;] = $proxyConfig[&apos;country&apos;] ?? &apos;rotating&apos;;\n        $options[&apos;headers&apos;][&apos;X-Proxy-Session&apos;] = $proxyConfig[&apos;session&apos;] ?? &apos;none&apos;;\n        \n        try {\n            return $this-&gt;client-&gt;request($method, $url, $options);\n        } catch (RequestException $e) {\n            \u002F\u002F Логируем ошибку с контекстом\n            $context = [\n                &apos;url&apos; =&gt; $url,\n                &apos;proxy_country&apos; =&gt; $proxyConfig[&apos;country&apos;] ?? &apos;rotating&apos;,\n                &apos;status_code&apos; =&gt; $e-&gt;hasResponse() ? $e-&gt;getResponse()-&gt;getStatusCode() : null,\n            ];\n            \n            throw new ProxyRequestException(\n                &quot;Proxy request failed: &quot; . $e-&gt;getMessage(),\n                $e-&gt;getCode(),\n                $e,\n                $context\n            );\n        }\n    }\n    \n    \u002F**\n     * Строит конфигурацию прокси для Guzzle\n     *\u002F\n    private function buildProxyConfig(array $options): array\n    {\n        $username = $this-&gt;username;\n        $session = $options[&apos;session&apos;] ?? null;\n        $country = $options[&apos;country&apos;] ?? null;\n        \n        \u002F\u002F Автоматическая ротация стран\n        if ($options[&apos;rotate_country&apos;] ?? false) {\n            $country = $this-&gt;countries[array_rand($this-&gt;countries)];\n        }\n        \n        \u002F\u002F Формируем имя пользователя с флагами\n        if ($country !== null) {\n            $username .= &quot;-country-{$country}&quot;;\n        }\n        \n        if ($session !== null) {\n            $username .= &quot;-sid-{$session}&quot;;\n        }\n        \n        \u002F\u002F URL для Guzzle: &apos;protocol:\u002F\u002Fuser:pass@host:port&apos;\n        $proxyUrl = sprintf(\n            &apos;http:\u002F\u002F%s:%s@%s:%d&apos;,\n            $username,\n            $this-&gt;password,\n            $this-&gt;proxyHost,\n            $this-&gt;proxyPort\n        );\n        \n        return [\n            &apos;url&apos; =&gt; $proxyUrl,\n            &apos;country&apos; =&gt; $country,\n            &apos;session&apos; =&gt; $session,\n        ];\n    }\n    \n    \u002F**\n     * Выполняет несколько запросов параллельно с разными прокси\n     *\u002F\n    public function batchRequest(array $requests): array\n    {\n        $promises = [];\n        \n        foreach ($requests as $key =&gt; $request) {\n            $proxyOptions = $request[&apos;proxy_options&apos;] ?? [];\n            $proxyConfig = $this-&gt;buildProxyConfig($proxyOptions);\n            \n            $promises[$key] = $this-&gt;client-&gt;requestAsync(\n                $request[&apos;method&apos;] ?? &apos;GET&apos;,\n                $request[&apos;url&apos;],\n                array_merge(\n                    $request[&apos;options&apos;] ?? [],\n                    [&apos;proxy&apos; =&gt; $proxyConfig[&apos;url&apos;]]\n                )\n            );\n        }\n        \n        \u002F\u002F Ждём завершения всех запросов\n        $results = \\GuzzleHttp\\Promise\\Utils::settle($promises)-&gt;wait();\n        \n        $responses = [];\n        foreach ($results as $key =&gt; $result) {\n            if ($result[&apos;state&apos;] === &apos;fulfilled&apos;) {\n                $responses[$key] = [\n                    &apos;success&apos; =&gt; true,\n                    &apos;response&apos; =&gt; $result[&apos;value&apos;],\n                    &apos;body&apos; =&gt; $result[&apos;value&apos;]-&gt;getBody()-&gt;getContents(),\n                ];\n            } else {\n                $responses[$key] = [\n                    &apos;success&apos; =&gt; false,\n                    &apos;error&apos; =&gt; $result[&apos;reason&apos;]-&gt;getMessage(),\n                ];\n            }\n        }\n        \n        return $responses;\n    }\n}\n\n\u002F\u002F Кастомное исключение с контекстом\nclass ProxyRequestException extends \\RuntimeException\n{\n    public array $context;\n    \n    public function __construct(string $message, int $code, \\Throwable $previous, array $context)\n    {\n        parent::__construct($message, $code, $previous);\n        $this-&gt;context = $context;\n    }\n}\n\n\u002F\u002F Использование:\n$client = new GuzzleProxyClient(&apos;user&apos;, &apos;your_password&apos;);\n\n\u002F\u002F Простой запрос с ротацией IP\n$response = $client-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;);\necho $response-&gt;getBody()-&gt;getContents();\n\n\u002F\u002F Запрос с конкретной страной\n$response = $client-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, [], [\n    &apos;country&apos; =&gt; &apos;DE&apos;,\n]);\n\n\u002F\u002F Sticky-сессия для многошагового скрейпинга\n$session = uniqid(&apos;session-&apos;, true);\n$client-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fexample.com\u002Flogin&apos;, [], [&apos;session&apos; =&gt; $session]);\n$client-&gt;request(&apos;POST&apos;, &apos;https:\u002F\u002Fexample.com\u002Flogin&apos;, [\n    &apos;form_params&apos; =&gt; [&apos;username&apos; =&gt; &apos;user&apos;, &apos;password&apos; =&gt; &apos;pass&apos;]\n], [&apos;session&apos; =&gt; $session]);\n$client-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fexample.com\u002Fdashboard&apos;, [], [&apos;session&apos; =&gt; $session]);\n\n\u002F\u002F Пакетные запросы с автоматической ротацией стран\n$results = $client-&gt;batchRequest([\n    &apos;us&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;US&apos;]],\n    &apos;de&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;DE&apos;]],\n    &apos;jp&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;JP&apos;]],\n]);\n\nforeach ($results as $region =&gt; $result) {\n    if ($result[&apos;success&apos;]) {\n        echo &quot;{$region}: &quot; . $result[&apos;body&apos;] . &quot;\\n&quot;;\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch3>Per-request ротация в Guzzle\u003C\u002Fh3>\n\n\u003Cp>Для скрейпинга часто нужен новый IP на каждый запрос. Guzzle позволяет переопределять прокси на уровне отдельного запроса:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nclass RotatingProxyPool\n{\n    private GuzzleProxyClient $client;\n    private array $sessions = [];\n    \n    public function __construct(GuzzleProxyClient $client)\n    {\n        $this-&gt;client = $client;\n    }\n    \n    \u002F**\n     * Получает новый IP для каждого запроса\n     *\u002F\n    public function fetchWithRotation(string $url): string\n    {\n        \u002F\u002F Без session-параметра ProxyHat выдаёт новый IP\n        return $this-&gt;client-&gt;request(&apos;GET&apos;, $url)-&gt;getBody()-&gt;getContents();\n    }\n    \n    \u002F**\n     * Создаёт sticky-сессию для последовательности запросов\n     *\u002F\n    public function createSession(string $country = null): string\n    {\n        $sessionId = bin2hex(random_bytes(8));\n        $this-&gt;sessions[$sessionId] = [\n            &apos;country&apos; =&gt; $country,\n            &apos;created_at&apos; =&gt; time(),\n        ];\n        return $sessionId;\n    }\n    \n    \u002F**\n     * Выполняет запрос в рамках сессии\n     *\u002F\n    public function fetchWithSession(string $url, string $sessionId): string\n    {\n        if (!isset($this-&gt;sessions[$sessionId])) {\n            throw new InvalidArgumentException(&quot;Unknown session: {$sessionId}&quot;);\n        }\n        \n        $session = $this-&gt;sessions[$sessionId];\n        \n        return $this-&gt;client-&gt;request(&apos;GET&apos;, $url, [], [\n            &apos;session&apos; =&gt; $sessionId,\n            &apos;country&apos; =&gt; $session[&apos;country&apos;],\n        ])-&gt;getBody()-&gt;getContents();\n    }\n    \n    \u002F**\n     * Очищает старые сессии (TTL 30 минут)\n     *\u002F\n    public function cleanupSessions(int $ttlSeconds = 1800): int\n    {\n        $now = time();\n        $count = 0;\n        \n        foreach ($this-&gt;sessions as $id =&gt; $session) {\n            if ($now - $session[&apos;created_at&apos;] &gt; $ttlSeconds) {\n                unset($this-&gt;sessions[$id]);\n                $count++;\n            }\n        }\n        \n        return $count;\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch2>Symfony HTTP Client: асинхронность и AsyncResponse\u003C\u002Fh2>\n\n\u003Cp>Symfony HTTP Client — современная библиотека с поддержкой асинхронных запросов, AMPHP и реактивного программирования. В отличие от Guzzle, Symfony HttpClient использует curl_multi под капотом и предоставляет нативную поддержку асинхронности без promises.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nrequire &apos;vendor\u002Fautoload.php&apos;;\n\nuse Symfony\\Component\\HttpClient\\HttpClient;\nuse Symfony\\Component\\HttpClient\\Response\\AsyncResponse;\nuse Symfony\\Contracts\\HttpClient\\Exception\\TransportExceptionInterface;\n\nclass SymfonyProxyClient\n{\n    private HttpClient $client;\n    private string $username;\n    private string $password;\n    private string $proxyHost = &apos;gate.proxyhat.com&apos;;\n    private int $proxyPort = 8080;\n    \n    public function __construct(string $username, string $password)\n    {\n        $this-&gt;username = $username;\n        $this-&gt;password = $password;\n        \n        $this-&gt;client = HttpClient::create([\n            &apos;timeout&apos; =&gt; 30,\n            &apos;max_redirects&apos; =&gt; 5,\n            &apos;verify_peer&apos; =&gt; true,\n            &apos;verify_host&apos; =&gt; true,\n            &apos;headers&apos; =&gt; [\n                &apos;User-Agent&apos; =&gt; &apos;Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36&apos;,\n            ],\n        ]);\n    }\n    \n    \u002F**\n     * Выполняет синхронный запрос через прокси\n     *\u002F\n    public function request(string $method, string $url, array $options = [], array $proxyOptions = []): array\n    {\n        $proxyUrl = $this-&gt;buildProxyUrl($proxyOptions);\n        \n        $mergedOptions = array_merge($options, [\n            &apos;proxy&apos; =&gt; $proxyUrl,\n        ]);\n        \n        try {\n            $response = $this-&gt;client-&gt;request($method, $url, $mergedOptions);\n            \n            return [\n                &apos;status&apos; =&gt; $response-&gt;getStatusCode(),\n                &apos;headers&apos; =&gt; $response-&gt;getHeaders(false),\n                &apos;body&apos; =&gt; $response-&gt;getContent(),\n                &apos;info&apos; =&gt; $response-&gt;getInfo(),\n            ];\n        } catch (TransportExceptionInterface $e) {\n            throw new ProxyTransportException(\n                &quot;Request failed: &quot; . $e-&gt;getMessage(),\n                $e-&gt;getCode(),\n                $e\n            );\n        }\n    }\n    \n    \u002F**\n     * Асинхронный запрос с колбэками\n     *\u002F\n    public function requestAsync(\n        string $method,\n        string $url,\n        array $options = [],\n        array $proxyOptions = [],\n        ?callable $onSuccess = null,\n        ?callable $onError = null\n    ): AsyncResponse {\n        $proxyUrl = $this-&gt;buildProxyUrl($proxyOptions);\n        \n        $mergedOptions = array_merge($options, [\n            &apos;proxy&apos; =&gt; $proxyUrl,\n        ]);\n        \n        return new AsyncResponse(\n            $this-&gt;client,\n            $method,\n            $url,\n            $mergedOptions,\n            function ($chunk, $response) use ($onSuccess, $onError) {\n                static $content = &apos;&apos;;\n                \n                try {\n                    \u002F\u002F Проверяем статус при первом чанке\n                    if ($response-&gt;getInfo(&apos;response_headers&apos;)) {\n                        $statusCode = $response-&gt;getStatusCode();\n                        \n                        if ($statusCode &gt;= 400) {\n                            if ($onError) {\n                                $onError(new \\Exception(&quot;HTTP {$statusCode}&quot;), $response);\n                            }\n                            return;\n                        }\n                    }\n                    \n                    \u002F\u002F Накапливаем контент\n                    if (is_string($chunk)) {\n                        $content .= $chunk;\n                    }\n                    \n                } catch (\\Exception $e) {\n                    if ($onError) {\n                        $onError($e, $response);\n                    }\n                }\n            },\n            function ($response) use ($onSuccess) {\n                \u002F\u002F Вызывается при завершении\n                if ($onSuccess) {\n                    $onSuccess($response);\n                }\n            }\n        );\n    }\n    \n    \u002F**\n     * Пакетные асинхронные запросы с ограничением конкурентности\n     *\u002F\n    public function batchAsync(array $requests, int $concurrency = 5): array\n    {\n        $responses = [];\n        $activeRequests = [];\n        $queue = $requests;\n        $results = [];\n        \n        \u002F\u002F Инициализируем первые N запросов\n        for ($i = 0; $i &lt; min($concurrency, count($queue)); $i++) {\n            $key = key($queue);\n            $request = array_shift($queue);\n            \n            $proxyOptions = $request[&apos;proxy_options&apos;] ?? [];\n            $proxyUrl = $this-&gt;buildProxyUrl($proxyOptions);\n            \n            $responses[$key] = $this-&gt;client-&gt;request(\n                $request[&apos;method&apos;] ?? &apos;GET&apos;,\n                $request[&apos;url&apos;],\n                array_merge($request[&apos;options&apos;] ?? [], [&apos;proxy&apos; =&gt; $proxyUrl])\n            );\n            \n            $activeRequests[] = $key;\n        }\n        \n        \u002F\u002F Обрабатываем ответы по мере поступления\n        $completed = [];\n        foreach (HttpClient::stream($responses) as $key =&gt; $chunk) {\n            try {\n                if ($chunk-&gt;isLast()) {\n                    $response = $responses[$key];\n                    $results[$key] = [\n                        &apos;success&apos; =&gt; true,\n                        &apos;status&apos; =&gt; $response-&gt;getStatusCode(),\n                        &apos;body&apos; =&gt; $response-&gt;getContent(),\n                    ];\n                    $completed[] = $key;\n                    \n                    \u002F\u002F Запускаем следующий запрос из очереди\n                    if (!empty($queue)) {\n                        $nextKey = key($queue);\n                        $nextRequest = array_shift($queue);\n                        \n                        $proxyUrl = $this-&gt;buildProxyUrl($nextRequest[&apos;proxy_options&apos;] ?? []);\n                        \n                        $responses[$nextKey] = $this-&gt;client-&gt;request(\n                            $nextRequest[&apos;method&apos;] ?? &apos;GET&apos;,\n                            $nextRequest[&apos;url&apos;],\n                            array_merge($nextRequest[&apos;options&apos;] ?? [], [&apos;proxy&apos; =&gt; $proxyUrl])\n                        );\n                    }\n                }\n            } catch (TransportExceptionInterface $e) {\n                $results[$key] = [\n                    &apos;success&apos; =&gt; false,\n                    &apos;error&apos; =&gt; $e-&gt;getMessage(),\n                ];\n                $completed[] = $key;\n            }\n        }\n        \n        return $results;\n    }\n    \n    \u002F**\n     * Стриминг больших файлов через прокси\n     *\u002F\n    public function downloadFile(\n        string $url,\n        string $destination,\n        array $proxyOptions = [],\n        ?callable $progressCallback = null\n    ): int {\n        $proxyUrl = $this-&gt;buildProxyUrl($proxyOptions);\n        \n        $response = $this-&gt;client-&gt;request(&apos;GET&apos;, $url, [\n            &apos;proxy&apos; =&gt; $proxyUrl,\n        ]);\n        \n        $handle = fopen($destination, &apos;w&apos;);\n        $bytesWritten = 0;\n        $contentLength = (int) ($response-&gt;getHeaders()[&apos;content-length&apos;][0] ?? 0);\n        \n        foreach ($this-&gt;client-&gt;stream($response) as $chunk) {\n            $bytesWritten += fwrite($handle, $chunk-&gt;getContent());\n            \n            if ($progressCallback) {\n                $progressCallback($bytesWritten, $contentLength);\n            }\n        }\n        \n        fclose($handle);\n        \n        return $bytesWritten;\n    }\n    \n    private function buildProxyUrl(array $options): string\n    {\n        $username = $this-&gt;username;\n        \n        if (isset($options[&apos;country&apos;])) {\n            $username .= &quot;-country-{$options[&apos;country&apos;]}&quot;;\n        }\n        \n        if (isset($options[&apos;session&apos;])) {\n            $username .= &quot;-sid-{$options[&apos;session&apos;]}&quot;;\n        }\n        \n        return &quot;http:\u002F\u002F{$username}:{$this-&gt;password}@{$this-&gt;proxyHost}:{$this-&gt;proxyPort}&quot;;\n    }\n}\n\n\u002F\u002F Использование:\n$client = new SymfonyProxyClient(&apos;user&apos;, &apos;your_password&apos;);\n\n\u002F\u002F Синхронный запрос\n$result = $client-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;);\necho $result[&apos;body&apos;];\n\n\u002F\u002F Асинхронные запросы с конкурентностью\n$results = $client-&gt;batchAsync([\n    &apos;us&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;US&apos;]],\n    &apos;de&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;DE&apos;]],\n    &apos;gb&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;proxy_options&apos; =&gt; [&apos;country&apos; =&gt; &apos;GB&apos;]],\n], concurrency: 3);\n\n\u002F\u002F Скачивание файла с прогрессом\n$client-&gt;downloadFile(\n    &apos;https:\u002F\u002Fexample.com\u002Flarge-file.zip&apos;,\n    &apos;\u002Ftmp\u002Ffile.zip&apos;,\n    [&apos;country&apos; =&gt; &apos;US&apos;],\n    fn($bytes, $total) =&gt; printf(&quot;Downloaded: %.1f%%\\r&quot;, ($bytes \u002F $total) * 100)\n);\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch2>Laravel интеграция: сервис-класс для Laravel proxy scraping\u003C\u002Fh2>\n\n\u003Cp>В Laravel-приложении прокси-клиент должен быть сервисом с dependency injection, конфигурацией через .env и интеграцией с очередями. Создадим production-ready решение.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\n\u002F\u002F config\u002Fproxy.php\n\nreturn [\n    &apos;default&apos; =&gt; env(&apos;PROXY_DRIVER&apos;, &apos;proxyhat&apos;),\n    \n    &apos;drivers&apos; =&gt; [\n        &apos;proxyhat&apos; =&gt; [\n            &apos;host&apos; =&gt; env(&apos;PROXY_HOST&apos;, &apos;gate.proxyhat.com&apos;),\n            &apos;http_port&apos; =&gt; env(&apos;PROXY_HTTP_PORT&apos;, 8080),\n            &apos;socks_port&apos; =&gt; env(&apos;PROXY_SOCKS_PORT&apos;, 1080),\n            &apos;username&apos; =&gt; env(&apos;PROXY_USERNAME&apos;),\n            &apos;password&apos; =&gt; env(&apos;PROXY_PASSWORD&apos;),\n        ],\n    ],\n    \n    &apos;defaults&apos; =&gt; [\n        &apos;timeout&apos; =&gt; env(&apos;PROXY_TIMEOUT&apos;, 30),\n        &apos;connect_timeout&apos; =&gt; env(&apos;PROXY_CONNECT_TIMEOUT&apos;, 10),\n        &apos;max_retries&apos; =&gt; env(&apos;PROXY_MAX_RETRIES&apos;, 3),\n        &apos;retry_delay&apos; =&gt; env(&apos;PROXY_RETRY_DELAY&apos;, 1000), \u002F\u002F ms\n    ],\n    \n    &apos;pool&apos; =&gt; [\n        &apos;countries&apos; =&gt; env(&apos;PROXY_COUNTRIES&apos;, &apos;US,DE,GB,FR,JP&apos;),\n        &apos;sticky_ttl&apos; =&gt; env(&apos;PROXY_STICKY_TTL&apos;, 1800), \u002F\u002F 30 минут\n    ],\n];\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\n\u002F\u002F app\u002FServices\u002FProxyService.php\n\nnamespace App\\Services;\n\nuse GuzzleHttp\\Client;\nuse GuzzleHttp\\Exception\\RequestException;\nuse GuzzleHttp\\HandlerStack;\nuse GuzzleHttp\\Middleware;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Psr\\Http\\Message\\RequestInterface;\nuse Psr\\Http\\Message\\ResponseInterface;\n\nclass ProxyService\n{\n    private Client $client;\n    private array $config;\n    private array $sessions = [];\n    \n    public function __construct(array $config = null)\n    {\n        $this-&gt;config = $config ?? config(&apos;proxy&apos;);\n        $this-&gt;client = $this-&gt;createClient();\n    }\n    \n    \u002F**\n     * Создаёт Guzzle-клиент с настройками прокси\n     *\u002F\n    private function createClient(): Client\n    {\n        $handlerStack = HandlerStack::create();\n        \n        \u002F\u002F Middleware для retry с экспоненциальной задержкой\n        $handlerStack-&gt;push($this-&gt;createRetryMiddleware());\n        \n        \u002F\u002F Middleware для логирования\n        if (config(&apos;app.debug&apos;) || config(&apos;proxy.logging.enabled&apos;, false)) {\n            $handlerStack-&gt;push($this-&gt;createLoggingMiddleware());\n        }\n        \n        return new Client([\n            &apos;handler&apos; =&gt; $handlerStack,\n            &apos;timeout&apos; =&gt; $this-&gt;config[&apos;defaults&apos;][&apos;timeout&apos;],\n            &apos;connect_timeout&apos; =&gt; $this-&gt;config[&apos;defaults&apos;][&apos;connect_timeout&apos;],\n            &apos;verify&apos; =&gt; true,\n            &apos;headers&apos; =&gt; $this-&gt;getDefaultHeaders(),\n        ]);\n    }\n    \n    \u002F**\n     * Middleware для повторных попыток\n     *\u002F\n    private function createRetryMiddleware(): callable\n    {\n        return Middleware::retry(\n            function ($retries, RequestInterface $request, ResponseInterface $response = null, $exception = null) {\n                $maxRetries = $this-&gt;config[&apos;defaults&apos;][&apos;max_retries&apos;];\n                \n                if ($retries &gt;= $maxRetries) {\n                    return false;\n                }\n                \n                \u002F\u002F Retry на 429, 5xx\n                if ($response) {\n                    $status = $response-&gt;getStatusCode();\n                    if (in_array($status, [429, 500, 502, 503, 504])) {\n                        Log::warning(&quot;Proxy request retrying&quot;, [\n                            &apos;status&apos; =&gt; $status,\n                            &apos;attempt&apos; =&gt; $retries + 1,\n                            &apos;url&apos; =&gt; (string) $request-&gt;getUri(),\n                        ]);\n                        return true;\n                    }\n                }\n                \n                \u002F\u002F Retry на сетевых ошибках\n                if ($exception instanceof \\GuzzleHttp\\Exception\\ConnectException) {\n                    Log::warning(&quot;Proxy connection error, retrying&quot;, [\n                        &apos;attempt&apos; =&gt; $retries + 1,\n                        &apos;error&apos; =&gt; $exception-&gt;getMessage(),\n                    ]);\n                    return true;\n                }\n                \n                return false;\n            },\n            function ($retries) {\n                $baseDelay = $this-&gt;config[&apos;defaults&apos;][&apos;retry_delay&apos;];\n                return $baseDelay * (2 ** $retries);\n            }\n        );\n    }\n    \n    \u002F**\n     * Middleware для логирования запросов\n     *\u002F\n    private function createLoggingMiddleware(): callable\n    {\n        return Middleware::tap(\n            function (RequestInterface $request, array $options) {\n                Log::debug(&apos;Proxy request started&apos;, [\n                    &apos;method&apos; =&gt; $request-&gt;getMethod(),\n                    &apos;url&apos; =&gt; (string) $request-&gt;getUri(),\n                    &apos;proxy&apos; =&gt; $options[&apos;proxy&apos;] ?? &apos;none&apos;,\n                ]);\n            },\n            function (RequestInterface $request, array $options, ResponseInterface $response) {\n                Log::debug(&apos;Proxy request completed&apos;, [\n                    &apos;status&apos; =&gt; $response-&gt;getStatusCode(),\n                    &apos;url&apos; =&gt; (string) $request-&gt;getUri(),\n                ]);\n            }\n        );\n    }\n    \n    \u002F**\n     * Выполняет HTTP-запрос через residential-прокси\n     *\u002F\n    public function request(\n        string $method,\n        string $url,\n        array $options = [],\n        ?string $country = null,\n        ?string $sessionId = null\n    ): array {\n        $proxyUrl = $this-&gt;buildProxyUrl($country, $sessionId);\n        \n        $mergedOptions = array_merge($options, [\n            &apos;proxy&apos; =&gt; $proxyUrl,\n        ]);\n        \n        $startTime = microtime(true);\n        \n        try {\n            $response = $this-&gt;client-&gt;request($method, $url, $mergedOptions);\n            \n            $this-&gt;recordMetrics(true, microtime(true) - $startTime, $country);\n            \n            return [\n                &apos;success&apos; =&gt; true,\n                &apos;status&apos; =&gt; $response-&gt;getStatusCode(),\n                &apos;headers&apos; =&gt; $response-&gt;getHeaders(),\n                &apos;body&apos; =&gt; (string) $response-&gt;getBody(),\n            ];\n        } catch (RequestException $e) {\n            $this-&gt;recordMetrics(false, microtime(true) - $startTime, $country);\n            \n            $response = $e-&gt;getResponse();\n            \n            return [\n                &apos;success&apos; =&gt; false,\n                &apos;status&apos; =&gt; $response?-&gt;getStatusCode() ?? 0,\n                &apos;error&apos; =&gt; $e-&gt;getMessage(),\n                &apos;body&apos; =&gt; $response ? (string) $response-&gt;getBody() : null,\n            ];\n        }\n    }\n    \n    \u002F**\n     * Создаёт sticky-сессию (тот же IP для всех запросов)\n     *\u002F\n    public function createSession(?string $country = null): string\n    {\n        $sessionId = uniqid(&apos;sess_&apos;, true);\n        $cacheKey = &quot;proxy_session:{$sessionId}&quot;;\n        \n        Cache::put($cacheKey, [\n            &apos;country&apos; =&gt; $country,\n            &apos;created_at&apos; =&gt; now()-&gt;timestamp,\n            &apos;request_count&apos; =&gt; 0,\n        ], now()-&gt;addSeconds($this-&gt;config[&apos;pool&apos;][&apos;sticky_ttl&apos;]));\n        \n        return $sessionId;\n    }\n    \n    \u002F**\n     * Выполняет запрос в рамках существующей сессии\n     *\u002F\n    public function requestWithSession(\n        string $method,\n        string $url,\n        string $sessionId,\n        array $options = []\n    ): array {\n        $cacheKey = &quot;proxy_session:{$sessionId}&quot;;\n        $session = Cache::get($cacheKey);\n        \n        if (!$session) {\n            throw new \\InvalidArgumentException(&quot;Session expired or not found: {$sessionId}&quot;);\n        }\n        \n        \u002F\u002F Обновляем счётчик запросов\n        $session[&apos;request_count&apos;]++;\n        Cache::put($cacheKey, $session, now()-&gt;addSeconds($this-&gt;config[&apos;pool&apos;][&apos;sticky_ttl&apos;]));\n        \n        return $this-&gt;request($method, $url, $options, $session[&apos;country&apos;], $sessionId);\n    }\n    \n    \u002F**\n     * Возвращает случайную страну из пула\n     *\u002F\n    public function getRandomCountry(): string\n    {\n        $countries = explode(&apos;,&apos;, $this-&gt;config[&apos;pool&apos;][&apos;countries&apos;]);\n        return $countries[array_rand($countries)];\n    }\n    \n    \u002F**\n     * Пакетные запросы с конкурентностью\n     *\u002F\n    public function batch(array $requests, int $concurrency = 5): array\n    {\n        $results = [];\n        $promises = [];\n        \n        foreach ($requests as $key =&gt; $request) {\n            $country = $request[&apos;country&apos;] ?? $this-&gt;getRandomCountry();\n            $proxyUrl = $this-&gt;buildProxyUrl($country, $request[&apos;session&apos;] ?? null);\n            \n            $promises[$key] = $this-&gt;client-&gt;requestAsync(\n                $request[&apos;method&apos;] ?? &apos;GET&apos;,\n                $request[&apos;url&apos;],\n                array_merge($request[&apos;options&apos;] ?? [], [&apos;proxy&apos; =&gt; $proxyUrl])\n            );\n        }\n        \n        \u002F\u002F Ждём завершения всех запросов\n        $responses = \\GuzzleHttp\\Promise\\Utils::settle($promises)-&gt;wait();\n        \n        foreach ($responses as $key =&gt; $result) {\n            if ($result[&apos;state&apos;] === &apos;fulfilled&apos;) {\n                $response = $result[&apos;value&apos;];\n                $results[$key] = [\n                    &apos;success&apos; =&gt; true,\n                    &apos;status&apos; =&gt; $response-&gt;getStatusCode(),\n                    &apos;body&apos; =&gt; (string) $response-&gt;getBody(),\n                ];\n            } else {\n                $results[$key] = [\n                    &apos;success&apos; =&gt; false,\n                    &apos;error&apos; =&gt; $result[&apos;reason&apos;]-&gt;getMessage(),\n                ];\n            }\n        }\n        \n        return $results;\n    }\n    \n    \u002F**\n     * Строит URL для прокси\n     *\u002F\n    private function buildProxyUrl(?string $country, ?string $sessionId): string\n    {\n        $driverConfig = $this-&gt;config[&apos;drivers&apos;][$this-&gt;config[&apos;default&apos;]];\n        \n        $username = $driverConfig[&apos;username&apos;];\n        \n        if ($country) {\n            $username .= &quot;-country-{$country}&quot;;\n        }\n        \n        if ($sessionId) {\n            $username .= &quot;-sid-{$sessionId}&quot;;\n        }\n        \n        $host = $driverConfig[&apos;host&apos;];\n        $port = $driverConfig[&apos;http_port&apos;];\n        $password = $driverConfig[&apos;password&apos;];\n        \n        return &quot;http:\u002F\u002F{$username}:{$password}@{$host}:{$port}&quot;;\n    }\n    \n    \u002F**\n     * Возвращает заголовки по умолчанию\n     *\u002F\n    private function getDefaultHeaders(): array\n    {\n        return [\n            &apos;User-Agent&apos; =&gt; config(&apos;proxy.user_agent&apos;, &apos;Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36&apos;),\n            &apos;Accept&apos; =&gt; &apos;text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8&apos;,\n            &apos;Accept-Language&apos; =&gt; &apos;en-US,en;q=0.9&apos;,\n        ];\n    }\n    \n    \u002F**\n     * Записывает метрики для мониторинга\n     *\u002F\n    private function recordMetrics(bool $success, float $duration, ?string $country): void\n    {\n        \u002F\u002F Интеграция с Laravel Pulse\u002Fmetrics\n        if (function_exists(&apos;metrics&apos;)) {\n            metrics()-&gt;increment(&apos;proxy.requests&apos;, 1, [\n                &apos;success&apos; =&gt; $success ? &apos;true&apos; : &apos;false&apos;,\n                &apos;country&apos; =&gt; $country ?? &apos;rotating&apos;,\n            ]);\n            \n            metrics()-&gt;timing(&apos;proxy.duration&apos;, $duration * 1000, [\n                &apos;country&apos; =&gt; $country ?? &apos;rotating&apos;,\n            ]);\n        }\n    }\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\n\u002F\u002F app\u002FJobs\u002FScrapeUrlJob.php\n\nnamespace App\\Jobs;\n\nuse App\\Services\\ProxyService;\nuse Illuminate\\Bus\\Queueable;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Foundation\\Bus\\Dispatchable;\nuse Illuminate\\Queue\\InteractsWithQueue;\nuse Illuminate\\Queue\\SerializesModels;\nuse Illuminate\\Support\\Facades\\Log;\nuse Exception;\n\nclass ScrapeUrlJob implements ShouldQueue\n{\n    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;\n    \n    public int $tries = 3;\n    public int $backoff = 10; \u002F\u002F секунд между попытками\n    \n    private string $url;\n    private ?string $country;\n    private ?string $sessionId;\n    private array $callbacks;\n    \n    public function __construct(\n        string $url,\n        ?string $country = null,\n        ?string $sessionId = null,\n        array $callbacks = []\n    ) {\n        $this-&gt;url = $url;\n        $this-&gt;country = $country;\n        $this-&gt;sessionId = $sessionId;\n        $this-&gt;callbacks = $callbacks;\n    }\n    \n    public function handle(ProxyService $proxyService): void\n    {\n        Log::info(&quot;Starting scrape job&quot;, [&apos;url&apos; =&gt; $this-&gt;url]);\n        \n        $result = $proxyService-&gt;request(\n            &apos;GET&apos;,\n            $this-&gt;url,\n            [],\n            $this-&gt;country,\n            $this-&gt;sessionId\n        );\n        \n        if (!$result[&apos;success&apos;]) {\n            Log::error(&quot;Scrape job failed&quot;, [\n                &apos;url&apos; =&gt; $this-&gt;url,\n                &apos;error&apos; =&gt; $result[&apos;error&apos;],\n            ]);\n            \n            throw new Exception($result[&apos;error&apos;]);\n        }\n        \n        \u002F\u002F Обрабатываем результат\n        $this-&gt;processResult($result);\n    }\n    \n    private function processResult(array $result): void\n    {\n        \u002F\u002F Парсинг HTML, извлечение данных, сохранение в БД\n        \u002F\u002F ...\n        \n        Log::info(&quot;Scrape job completed&quot;, [\n            &apos;url&apos; =&gt; $this-&gt;url,\n            &apos;status&apos; =&gt; $result[&apos;status&apos;],\n            &apos;size&apos; =&gt; strlen($result[&apos;body&apos;]),\n        ]);\n    }\n    \n    \u002F**\n     * Обработка неудачной задачи\n     *\u002F\n    public function failed(Exception $exception): void\n    {\n        Log::error(&quot;Scrape job permanently failed&quot;, [\n            &apos;url&apos; =&gt; $this-&gt;url,\n            &apos;exception&apos; =&gt; $exception-&gt;getMessage(),\n        ]);\n    }\n}\n\n\u002F\u002F Использование в контроллере или сервисе:\n\n\u002F\u002F Простой запрос\n$proxyService = app(ProxyService::class);\n$result = $proxyService-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fexample.com\u002Fdata&apos;);\n\n\u002F\u002F С геотаргетингом\n$result = $proxyService-&gt;request(&apos;GET&apos;, &apos;https:\u002F\u002Fexample.com\u002Fdata&apos;, [], &apos;US&apos;);\n\n\u002F\u002F Sticky-сессия для многошагового скрейпинга\n$sessionId = $proxyService-&gt;createSession(&apos;DE&apos;);\n$proxyService-&gt;requestWithSession(&apos;GET&apos;, &apos;https:\u002F\u002Fexample.com\u002Flogin&apos;, $sessionId);\n$proxyService-&gt;requestWithSession(&apos;POST&apos;, &apos;https:\u002F\u002Fexample.com\u002Flogin&apos;, $sessionId, [\n    &apos;form_params&apos; =&gt; [&apos;username&apos; =&gt; &apos;user&apos;, &apos;password&apos; =&gt; &apos;pass&apos;]\n]);\n\n\u002F\u002F Диспетчеризация в очередь\nScrapeUrlJob::dispatch(&apos;https:\u002F\u002Fexample.com\u002Fdata&apos;, &apos;US&apos;);\n\n\u002F\u002F Пакетная обработка\n$results = $proxyService-&gt;batch([\n    &apos;us&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;country&apos; =&gt; &apos;US&apos;],\n    &apos;de&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;country&apos; =&gt; &apos;DE&apos;],\n    &apos;gb&apos; =&gt; [&apos;url&apos; =&gt; &apos;https:\u002F\u002Fhttpbin.org\u002Fip&apos;, &apos;country&apos; =&gt; &apos;GB&apos;],\n]);\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch2>Multi-curl для конкурентного скрейпинга\u003C\u002Fh2>\n\n\u003Cp>Когда нужно выполнить сотни запросов параллельно, multi_curl — самый эффективный способ. Он использует один процесс и не требует внешних зависимостей.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nclass MultiCurlProxyClient\n{\n    private string $proxyHost = &apos;gate.proxyhat.com&apos;;\n    private int $proxyPort = 8080;\n    private string $username;\n    private string $password;\n    private int $maxConnections = 10;\n    private int $timeout = 30;\n    \n    public function __construct(string $username, string $password)\n    {\n        $this-&gt;username = $username;\n        $this-&gt;password = $password;\n    }\n    \n    \u002F**\n     * Выполняет массив запросов параллельно\n     * \n     * @param array $requests Массив [&apos;key&apos; =&gt; [&apos;url&apos; =&gt; &apos;...&apos;, &apos;options&apos; =&gt; [...]]]\n     * @param callable $progressCallback Колбэк прогресса (optional)\n     * @return array Результаты по ключам\n     *\u002F\n    public function fetchAll(array $requests, ?callable $progressCallback = null): array\n    {\n        $results = [];\n        $handles = [];\n        \n        \u002F\u002F Создаём multi-handle\n        $mh = curl_multi_init();\n        \n        \u002F\u002F Настройка multi-handle\n        curl_multi_setopt($mh, CURLMOPT_MAX_TOTAL_CONNECTIONS, $this-&gt;maxConnections);\n        \n        \u002F\u002F Создаём индивидуальные handles\n        foreach ($requests as $key =&gt; $request) {\n            $ch = $this-&gt;createHandle($request[&apos;url&apos;], $request[&apos;options&apos;] ?? []);\n            $handles[$key] = [\n                &apos;handle&apos; =&gt; $ch,\n                &apos;url&apos; =&gt; $request[&apos;url&apos;],\n            ];\n            curl_multi_add_handle($mh, $ch);\n        }\n        \n        \u002F\u002F Выполняем запросы\n        $active = null;\n        $completed = 0;\n        $total = count($requests);\n        \n        do {\n            $status = curl_multi_exec($mh, $active);\n            \n            if ($status === CURLM_OK) {\n                \u002F\u002F Ждём активности\n                curl_multi_select($mh, 1.0);\n            }\n            \n            \u002F\u002F Проверяем завершённые запросы\n            while (($info = curl_multi_info_read($mh)) !== false) {\n                if ($info[&apos;msg&apos;] === CURLMSG_DONE) {\n                    $ch = $info[&apos;handle&apos;];\n                    \n                    \u002F\u002F Находим ключ по handle\n                    $key = $this-&gt;findKeyByHandle($handles, $ch);\n                    \n                    if ($key !== null) {\n                        $results[$key] = $this-&gt;processResult($ch, $info[&apos;result&apos;]);\n                        $completed++;\n                        \n                        if ($progressCallback) {\n                            $progressCallback($completed, $total, $key, $results[$key]);\n                        }\n                    }\n                    \n                    curl_multi_remove_handle($mh, $ch);\n                    curl_close($ch);\n                    unset($handles[$key]);\n                }\n            }\n            \n        } while ($status === CURLM_CALL_MULTI_PERFORM || $active &gt; 0);\n        \n        curl_multi_close($mh);\n        \n        return $results;\n    }\n    \n    \u002F**\n     * Выполняет запросы с ограничением скорости (rate limiting)\n     *\u002F\n    public function fetchWithRateLimit(\n        array $requests,\n        int $requestsPerSecond = 5,\n        ?callable $progressCallback = null\n    ): array {\n        $results = [];\n        $batchSize = $this-&gt;maxConnections;\n        $delayBetweenBatches = (1000 * $batchSize) \u002F $requestsPerSecond;\n        \n        $batches = array_chunk($requests, $batchSize, true);\n        \n        foreach ($batches as $batchIndex =&gt; $batch) {\n            if ($batchIndex &gt; 0) {\n                usleep((int) $delayBetweenBatches * 1000);\n            }\n            \n            $batchResults = $this-&gt;fetchAll($batch, $progressCallback);\n            $results = array_merge($results, $batchResults);\n        }\n        \n        return $results;\n    }\n    \n    \u002F**\n     * Создаёт cURL handle для запроса\n     *\u002F\n    private function createHandle(string $url, array $options = []): \\CurlHandle\n    {\n        $ch = curl_init();\n        \n        \u002F\u002F Формируем URL прокси с параметрами\n        $proxyUser = $this-&gt;username;\n        \n        if (isset($options[&apos;country&apos;])) {\n            $proxyUser .= &quot;-country-{$options[&apos;country&apos;]}&quot;;\n        }\n        \n        if (isset($options[&apos;session&apos;])) {\n            $proxyUser .= &quot;-sid-{$options[&apos;session&apos;]}&quot;;\n        }\n        \n        curl_setopt_array($ch, [\n            CURLOPT_URL =&gt; $url,\n            CURLOPT_RETURNTRANSFER =&gt; true,\n            CURLOPT_FOLLOWLOCATION =&gt; true,\n            CURLOPT_MAXREDIRS =&gt; 5,\n            CURLOPT_TIMEOUT =&gt; $options[&apos;timeout&apos;] ?? $this-&gt;timeout,\n            CURLOPT_CONNECTTIMEOUT =&gt; $options[&apos;connect_timeout&apos;] ?? 10,\n            \n            \u002F\u002F Прокси\n            CURLOPT_PROXY =&gt; $this-&gt;proxyHost,\n            CURLOPT_PROXYPORT =&gt; $this-&gt;proxyPort,\n            CURLOPT_PROXYUSERPWD =&gt; &quot;{$proxyUser}:{$this-&gt;password}&quot;,\n            CURLOPT_PROXYTYPE =&gt; CURLPROXY_HTTP,\n            \n            \u002F\u002F SSL\n            CURLOPT_SSL_VERIFYPEER =&gt; true,\n            CURLOPT_SSL_VERIFYHOST =&gt; 2,\n            \n            \u002F\u002F Заголовки\n            CURLOPT_USERAGENT =&gt; $options[&apos;user_agent&apos;] ?? &apos;Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36&apos;,\n            CURLOPT_HTTPHEADER =&gt; $options[&apos;headers&apos;] ?? [],\n            \n            \u002F\u002F Для захвата заголовков\n            CURLOPT_HEADER =&gt; true,\n        ]);\n        \n        \u002F\u002F POST-данные если есть\n        if (isset($options[&apos;post_data&apos;])) {\n            curl_setopt($ch, CURLOPT_POST, true);\n            curl_setopt($ch, CURLOPT_POSTFIELDS, $options[&apos;post_data&apos;]);\n        }\n        \n        \u002F\u002F Кастомный метод\n        if (isset($options[&apos;method&apos;])) {\n            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options[&apos;method&apos;]);\n        }\n        \n        return $ch;\n    }\n    \n    \u002F**\n     * Обрабатывает результат запроса\n     *\u002F\n    private function processResult(\\CurlHandle $ch, int $curlResult): array\n    {\n        $response = curl_multi_getcontent($ch);\n        $info = curl_getinfo($ch);\n        $error = curl_error($ch);\n        \n        if ($curlResult !== CURLE_OK) {\n            return [\n                &apos;success&apos; =&gt; false,\n                &apos;error&apos; =&gt; $error,\n                &apos;error_code&apos; =&gt; $curlResult,\n            ];\n        }\n        \n        $headerSize = $info[&apos;header_size&apos;];\n        \n        return [\n            &apos;success&apos; =&gt; true,\n            &apos;status&apos; =&gt; $info[&apos;http_code&apos;],\n            &apos;headers&apos; =&gt; substr($response, 0, $headerSize),\n            &apos;body&apos; =&gt; substr($response, $headerSize),\n            &apos;info&apos; =&gt; [\n                &apos;total_time&apos; =&gt; $info[&apos;total_time&apos;],\n                &apos;connect_time&apos; =&gt; $info[&apos;connect_time&apos;],\n                &apos;size_download&apos; =&gt; $info[&apos;size_download&apos;],\n                &apos;effective_url&apos; =&gt; $info[&apos;url&apos;],\n            ],\n        ];\n    }\n    \n    \u002F**\n     * Находит ключ по handle в массиве\n     *\u002F\n    private function findKeyByHandle(array $handles, \\CurlHandle $ch): ?string\n    {\n        foreach ($handles as $key =&gt; $data) {\n            if ($data[&apos;handle&apos;] === $ch) {\n                return $key;\n            }\n        }\n        return null;\n    }\n}\n\n\u002F\u002F Использование:\n$client = new MultiCurlProxyClient(&apos;user&apos;, &apos;your_password&apos;);\n$client-&gt;setMaxConnections(20);\n\n\u002F\u002F Генерируем список URL для скрейпинга\n$urls = [];\nfor ($i = 1; $i &lt;= 100; $i++) {\n    $urls[&quot;page_{$i}&quot;] = [\n        &apos;url&apos; =&gt; &quot;https:\u002F\u002Fexample.com\u002Fpage\u002F{$i}&quot;,\n        &apos;options&apos; =&gt; [&apos;country&apos; =&gt; &apos;US&apos;],\n    ];\n}\n\n\u002F\u002F Выполняем с прогрессом\n$results = $client-&gt;fetchAll($urls, function ($completed, $total, $key, $result) {\n    echo sprintf(&quot;[%d\u002F%d] %s: %s\\n&quot;, $completed, $total, $key, \n        $result[&apos;success&apos;] ? &quot;OK ({$result[&apos;status&apos;]})&quot; : &quot;ERROR: {$result[&apos;error&apos;]}&quot;\n    );\n});\n\n\u002F\u002F С rate limiting (10 запросов в секунду)\n$results = $client-&gt;fetchWithRateLimit($urls, 10);\n\n\u002F\u002F Анализ результатов\n$successCount = count(array_filter($results, fn($r) =&gt; $r[&apos;success&apos;]));\necho &quot;Успешных запросов: {$successCount} из &quot; . count($results) . &quot;\\n&quot;;\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch2>TLS\u002FSSL конфигурация и CA-бандлы\u003C\u002Fh2>\n\n\u003Cp>При работе через прокси критически важна правильная настройка TLS. Ошибки SSL могут маскироваться под проблемы с прокси, хотя на самом деле это отсутствие актуальных корневых сертификатов.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode>&lt;?php\n\nclass TlsProxyClient\n{\n    private ?string $caBundlePath = null;\n    private array $sslOptions = [];\n    \n    public function __construct()\n    {\n        $this-&gt;caBundlePath = $this-&gt;detectCaBundle();\n        $this-&gt;configureSsl();\n    }\n    \n    \u002F**\n     * Определяет путь к CA-бандлу\n     *\u002F\n    private function detectCaBundle(): string\n    {\n        \u002F\u002F Приоритет поиска CA-бандла\n        $candidates = [\n            \u002F\u002F Переменная окружения\n            getenv(&apos;SSL_CERT_FILE&apos;) ?: null,\n            \n            \u002F\u002F Системные пути (Linux)\n            &apos;\u002Fetc\u002Fssl\u002Fcerts\u002Fca-certificates.crt&apos;,           \u002F\u002F Debian\u002FUbuntu\u002FGentoo\n            &apos;\u002Fetc\u002Fpki\u002Ftls\u002Fcerts\u002Fca-bundle.crt&apos;,              \u002F\u002F RHEL\u002FCentOS\u002FFedora\n            &apos;\u002Fetc\u002Fssl\u002Fca-bundle.pem&apos;,                        \u002F\u002F OpenSUSE\n            &apos;\u002Fetc\u002Fpki\u002Ftls\u002Fcacert.pem&apos;,                       \u002F\u002F Alpine\n            &apos;\u002Fetc\u002Fssl\u002Fcert.pem&apos;,                             \u002F\u002F Alpine (альтернативный)\n            &apos;\u002Fusr\u002Flocal\u002Fshare\u002Fcerts\u002Fca-root-nss.crt&apos;,       \u002F\u002F FreeBSD\n            &apos;\u002Fetc\u002Fpki\u002Fca-trust\u002Fextracted\u002Fpem\u002Ftls-ca-bundle.pem&apos;, \u002F\u002F RHEL (новые версии)\n            \n            \u002F\u002F macOS\n            &apos;\u002Fusr\u002Flocal\u002Fetc\u002Fopenssl\u002Fcert.pem&apos;,\n            &apos;\u002Fusr\u002Flocal\u002Fetc\u002Fopenssl@1.1\u002Fcert.pem&apos;,\n            &apos;\u002Fusr\u002Flocal\u002Fetc\u002Fopenssl@3\u002Fcert.pem&apos;,\n            \n            \u002F\u002F Windows (при использовании WAMP\u002FXAMPP)\n            &apos;C:\\\\wamp64\\\\bin\\\\php\\\\php7.4\\\\extras\\\\ssl\\\\cacert.pem&apos;,\n            &apos;C:\\\\xampp\\\\php\\\\extras\\\\ssl\\\\cacert.pem&apos;,\n            \n            \u002F\u002F Composer CA-бандл (если установлен)\n            dirname(__DIR__) . &apos;\u002Fvendor\u002Fcomposer\u002Fca-bundle\u002Fres\u002Fcacert.pem&apos;,\n            \n            \u002F\u002F Локальный fallback\n            __DIR__ . &apos;\u002Fcacert.pem&apos;,\n        ];\n        \n        foreach ($candidates as $path) {\n            if ($path &amp;&amp; file_exists($path) &amp;&amp; is_readable($path)) {\n                return $path;\n            }\n        }\n        \n        \u002F\u002F Скачиваем Mozilla CA bundle если ничего не найдено\n        return $this-&gt;downloadCaBundle();\n    }\n    \n    \u002F**\n     * Скачивает актуальный CA-бандл от Mozilla\n     *\u002F\n    private function downloadCaBundle(): string\n    {\n        $targetPath = sys_get_temp_dir() . &apos;\u002Fcacert-&apos; . date(&apos;Y-m&apos;) . &apos;.pem&apos;;\n        \n        if (file_exists($targetPath)) {\n            return $targetPath;\n        }\n        \n        $source = &apos;https:\u002F\u002Fcurl.se\u002Fca\u002Fcacert.pem&apos;;\n        $tempFile = tempnam(sys_get_temp_dir(), &apos;cacert&apos;);\n        \n        \u002F\u002F Скачиваем без верификации (bootstrapping)\n        $ch = curl_init($source);\n        curl_setopt_array($ch, [\n            CURLOPT_RETURNTRANSFER =&gt; true,\n            CURLOPT_SSL_VERIFYPEER =&gt; false, \u002F\u002F Только для начального скачивания!\n            CURLOPT_FOLLOWLOCATION =&gt; true,\n        ]);\n        \n        $data = curl_exec($ch);\n        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);\n        curl_close($ch);\n        \n        if ($code === 200 &amp;&amp; $data) {\n            file_put_contents($tempFile, $data);\n            rename($tempFile, $targetPath);\n            return $targetPath;\n        }\n        \n        throw new RuntimeException(&apos;Failed to download CA bundle&apos;);\n    }\n    \n    \u002F**\n     * Настраивает SSL-опции\n     *\u002F\n    private function configureSsl(): void\n    {\n        $this-&gt;sslOptions = [\n            &apos;verify_peer&apos; =&gt; true,\n            &apos;verify_peer_name&apos; =&gt; true,\n            &apos;verify_host&apos; =&gt; 2,\n            &apos;ca_info&apos; =&gt; $this-&gt;caBundlePath,\n            \n            \u002F\u002F Минимальная версия TLS\n            &apos;ssl_version&apos; =&gt; CURL_SSLVERSION_TLSv1_2,\n            \n            \u002F\u002F Шифры (приоритет безопасных)\n            &apos;ssl_cipher_list&apos; =&gt; &apos;TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256&apos;,\n        ];\n    }\n    \n    \u002F**\n     * Возвращает опции cURL для SSL\n     *\u002F\n    public function getCurlSslOptions(): array\n    {\n        return [\n            CURLOPT_SSL_VERIFYPEER =&gt; $this-&gt;sslOptions[&apos;verify_peer&apos;],\n            CURLOPT_SSL_VERIFYHOST =&gt; $this-&gt;sslOptions[&apos;verify_host&apos;],\n            CURLOPT_CAINFO =&gt; $this-&gt;sslOptions[&apos;ca_info&apos;],\n            CURLOPT_SSLVERSION =&gt; $this-&gt;sslOptions[&apos;ssl_version&apos;],\n            CURLOPT_SSL_CIPHER_LIST =&gt; $this-&gt;sslOptions[&apos;ssl_cipher_list&apos;],\n        ];\n    }\n    \n    \u002F**\n     * Возвращает опции для Guzzle\n     *\u002F\n    public function getGuzzleSslOptions(): array\n    {\n        return [\n            &apos;verify&apos; =&gt; $this-&gt;sslOptions[&apos;ca_info&apos;],\n        ];\n    }\n    \n    \u002F**\n     * Возвращает опции для Symfony HttpClient\n     *\u002F\n    public function getSymfonySslOptions(): array\n    {\n        return [\n            &apos;verify_peer&apos; =&gt; $this-&gt;sslOptions[&apos;verify_peer&apos;],\n            &apos;verify_host&apos; =&gt; $this-&gt;sslOptions[&apos;verify_host&apos;],\n            &apos;cafile&apos; =&gt; $this-&gt;sslOptions[&apos;ca_info&apos;],\n        ];\n    }\n    \n    \u002F**\n     * Проверяет SSL-соединение через прокси\n     *\u002F\n    public function testSslConnection(string $proxyUrl, string $testUrl = &apos;https:\u002F\u002Fwww.google.com&apos;): array\n    {\n        $ch = curl_init($testUrl);\n        \n        curl_setopt_array($ch, [\n            CURLOPT_RETURNTRANSFER =&gt; true,\n            CURLOPT_PROXY =&gt; $proxyUrl,\n            CURLOPT_TIMEOUT =&gt; 10,\n        ] + $this-&gt;getCurlSslOptions());\n        \n        $response = curl_exec($ch);\n        $info = curl_getinfo($ch);\n        $error = curl_error($ch);\n        $errno = curl_errno($ch);\n        \n        curl_close($ch);\n        \n        return [\n            &apos;success&apos; =&gt; $errno === CURLE_OK &amp;&amp; $info[&apos;http_code&apos;] === 200,\n            &apos;http_code&apos; =&gt; $info[&apos;http_code&apos;],\n            &apos;ssl_verify_result&apos; =&gt; $info[&apos;ssl_verify_result&apos;],\n            &apos;error&apos; =&gt; $error ?: null,\n            &apos;ca_path&apos; =&gt; $this-&gt;caBundlePath,\n            &apos;cert_info&apos; =&gt; $info[&apos;certinfo&apos;] ?? [],\n        ];\n    }\n    \n    \u002F**\n     * Отключает верификацию (только для разработки!)\n     *\u002F\n    public function disableVerification(): void\n    {\n        if (getenv(&apos;APP_ENV&apos;) === &apos;production&apos;) {\n            throw new RuntimeException(&apos;Cannot disable SSL verification in production&apos;);\n        }\n        \n        $this-&gt;sslOptions[&apos;verify_peer&apos;] = false;\n        $this-&gt;sslOptions[&apos;verify_peer_name&apos;] = false;\n        $this-&gt;sslOptions[&apos;verify_host&apos;] = 0;\n    }\n}\n\n\u002F\u002F Использование:\n$sslClient = new TlsProxyClient();\n\n\u002F\u002F Проверяем путь к CA\n echo &quot;CA Bundle: &quot; . $sslClient-&gt;caBundlePath . &quot;\\n&quot;;\n\n\u002F\u002F Тестируем SSL через прокси\n$proxyUrl = &apos;http:\u002F\u002Fuser-country-US:password@gate.proxyhat.com:8080&apos;;\n$result = $sslClient-&gt;testSslConnection($proxyUrl);\n\nif ($result[&apos;success&apos;]) {\n    echo &quot;SSL-соединение успешно\\n&quot;;\n} else {\n    echo &quot;SSL-ошибка: &quot; . $result[&apos;error&apos;] . &quot;\\n&quot;;\n}\n\n\u002F\u002F Интеграция с Guzzle\n$guzzleOptions = $sslClient-&gt;getGuzzleSslOptions();\n$client = new GuzzleHttp\\Client($guzzleOptions);\n\n\u002F\u002F Интеграция с Symfony HttpClient\n$symfonyOptions = $sslClient-&gt;getSymfonySslOptions();\n$client = Symfony\\Component\\HttpClient\\HttpClient::create($symfonyOptions);\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Ch2>Сравнение подходов\u003C\u002Fh2>\n\n\u003Cp>Выбор библиотеки зависит от требований проекта:\u003C\u002Fp>\n\n\u003Ctable>\n\u003Cthead>\n\u003Ctr>\n\u003Cth>Критерий\u003C\u002Fth>\n\u003Cth>cURL\u003C\u002Fth>\n\u003Cth>Guzzle\u003C\u002Fth>\n\u003Cth>Symfony HttpClient\u003C\u002Fth>\n\u003Cth>Multi-curl\u003C\u002Fth>\n\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\n\u003Ctd>Сложность\u003C\u002Ftd>\n\u003Ctd>Низкая\u003C\u002Ftd>\n\u003Ctd>Средняя\u003C\u002Ftd>\n\u003Ctd>Средняя\u003C\u002Ftd>\n\u003Ctd>Высокая\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>Асинхронность\u003C\u002Ftd>\n\u003Ctd>Нет\u003C\u002Ftd>\n\u003Ctd>Через promises\u003C\u002Ftd>\n\u003Ctd>Нативная\u003C\u002Ftd>\n\u003Ctd>Нативная\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>Производительность\u003C\u002Ftd>\n\u003Ctd>Базовая\u003C\u002Ftd>\n\u003Ctd>Хорошая\u003C\u002Ftd>\n\u003Ctd>Отличная\u003C\u002Ftd>\n\u003Ctd>Максимальная\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>Интеграция с Laravel\u003C\u002Ftd>\n\u003Ctd>Ручная\u003C\u002Ftd>\n\u003Ctd>Нативная\u003C\u002Ftd>\n\u003Ctd>Через HTTP-клиент\u003C\u002Ftd>\n\u003Ctd>Ручная\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>Retry-логика\u003C\u002Ftd>\n\u003Ctd>Ручная\u003C\u002Ftd>\n\u003Ctd>Middleware\u003C\u002Ftd>\n\u003Ctd>Callback\u003C\u002Ftd>\n\u003Ctd>Ручная\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>Подходит для\u003C\u002Ftd>\n\u003Ctd>Простые запросы\u003C\u002Ftd>\n\u003Ctd>API-интеграции\u003C\u002Ftd>\n\u003Ctd>Реактивные приложения\u003C\u002Ftd>\n\u003Ctd>Массовый скрейпинг\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\n\u003Cblockquote>\n\u003Cp>Рекомендация: Для Laravel proxy scraping используйте Guzzle с middleware для retry и логирования. Для высоконагруженного массового скрейпинга — multi_curl с пулом соединений.\u003C\u002Fp>\n\u003C\u002Fblockquote>\n\n\u003Ch2>Лучшие практики для production\u003C\u002Fh2>\n\n\u003Cul>\n\u003Cli>Всегда включайте верификацию SSL — никогда не отключайте CURLOPT_SSL_VERIFYPEER в production. Используйте актуальный CA-бандл.\u003C\u002Fli>\n\u003Cli>Настраивайте таймауты — connect_timeout 5-10 секунд, общий timeout 30 секунд для обычных запросов, до 120 для больших файлов.\u003C\u002Fli>\n\u003Cli>Реализуйте circuit breaker — при серии неудач временно отключайте прокси и переключайтесь на резервный.\u003C\u002Fli>\n\u003Cli>Логируйте метрики —成功率, latency, ошибки по странам. Это поможет выявить проблемные регионы.\u003C\u002Fli>\n\u003Cli>Уважайте robots.txt и rate limits — даже с rotating proxies агрессивный скрейпинг приведёт к блокировкам.\u003C\u002Fli>\n\u003Cli>Используйте sticky-сессии для multi-step — логин, навигация, получение данных должны идти через один IP.\u003C\u002Fli>\n\u003Cli>Кэшируйте ответы — для SERP и ценовых данных кэш на 1-24 часа существенно снизит нагрузку.\u003C\u002Fli>\n\u003C\u002Ful>\n\n\u003Cp>Готовы начать? \u003Ca href=\"\u002Fru\u002Fpricing\">Изучите тарифы ProxyHat\u003C\u002Fa> и получите доступ к пулу residential и mobile прокси для ваших PHP-проектов. Для массового скрейпинга ознакомьтесь с \u003Ca href=\"\u002Fru\u002Fuse-cases\u002Fweb-scraping\">кейсом по сбору данных\u003C\u002Fa>.\u003C\u002Fp>","PHP Proxy: Guzzle, cURL и Laravel — полное руководство | ProxyHat","Научитесь работать с HTTP-прокси в PHP: нативный cURL, Guzzle, Symfony HttpClient, интеграция с Laravel. Примеры кода, TLS\u002FSSL, ротация IP и конкурентные запросы.","\u002Fru\u002Fblog\u002Fhttp-proksi-php-guzzle-laravel",null,"PHP Proxy: Guzzle, cURL и Laravel — руководство","Полное руководство по работе с HTTP-прокси в PHP. Примеры кода для cURL, Guzzle, Symfony HttpClient и интеграции с Laravel.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fai\u002F61.jpg",[19,22,25,28,31],{"question":20,"answer":21},"Как настроить прокси в PHP через cURL?","Используйте опции CURLOPT_PROXY (хост прокси), CURLOPT_PROXYPORT (порт) и CURLOPT_PROXYUSERPWD (авторизация в формате username:password). Для ProxyHat: CURLOPT_PROXY = 'gate.proxyhat.com', CURLOPT_PROXYPORT = 8080, CURLOPT_PROXYUSERPWD = 'user-country-US:password'.",{"question":23,"answer":24},"Как сделать ротацию IP в Guzzle?","Передавайте опцию 'proxy' в каждом запросе с разными параметрами сессии. Без session-параметра ProxyHat выдаёт новый IP. Для sticky-сессии добавьте session-ID к username: 'user-sid-abc123:password'.",{"question":26,"answer":27},"Какой HTTP-клиент выбрать для скрейпинга в PHP?","Guzzle — для API-интеграций и Laravel-проектов (PSR-7, middleware, retry). Symfony HttpClient — для асинхронных приложений. Multi-curl — для максимальной производительности при массовых запросах (сотни URL).",{"question":29,"answer":30},"Как исправить SSL-ошибки при работе через прокси?","Убедитесь, что CURLOPT_CAINFO указывает на актуальный CA-бандл. Скачайте cacert.pem с curl.se\u002Fca\u002Fcacert.pem или используйте системный путь (\u002Fetc\u002Fssl\u002Fcerts\u002Fca-certificates.crt на Linux). Никогда не отключайте SSL_VERIFYPEER в production.",{"question":32,"answer":33},"Как использовать sticky-сессии в ProxyHat?","Добавьте session-ID к имени пользователя: 'user-sid-abc123:password'. ProxyHat будет использовать тот же IP для всех запросов с этой сессией. TTL сессии — до 30 минут. Идеально для многошагового скрейпинга (логин, навигация, извлечение данных).",[35,36,37,38,39],"Использование HTTP-прокси в PHP требует не только настройки CURLOPT_PROXY, но и ротации IP, обработки ошибок и TLS-конфигурации.","В cURL авторизация и геотаргетинг настраиваются через CURLOPT_PROXYUSERPWD путем добавления флагов к имени пользователя.","Guzzle поддерживает переопределение прокси для каждого запроса, пакетные запросы и автоматические повторные попытки.","Sticky-сессии гарантируют использование одного IP-адреса на протяжении всей сессии, что важно для многошагового скрейпинга.","Для корректной работы HTTPS через прокси необходимо указать правильный путь к CA-бандлу в настройках TLS-верификации.",false,"2026-04-21T09:58:05+00:00","2026-11-17T09:21:32+00:00",15,{"name":45,"slug":46,"bio":47,"avatar_url":14,"website_url":14,"social_links":14},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[49],{"id":50,"slug":51,"name":52,"description":14,"meta_title":53,"meta_description":54,"parent_id":14},4,"rukovodstva-dlya-razrabotchikov","Руководства для разработчиков","Руководства для разработчиков | Блог ProxyHat","Туториалы по коду и SDK для интеграции прокси в ваши приложения.",[],{"en":57,"ru":13,"x-default":57},"\u002Fblog\u002Fphp-http-proxy-guide-guzzle-laravel",{"en":57,"ko":59,"pl":60,"es":61,"fr":62,"ru":13,"de":63,"tr":64,"pt":65,"zh":66,"ja":67,"it":68},"\u002Fko\u002Fblog\u002Fphp-http-proxy-guzzle-laravel-guide","\u002Fpl\u002Fblog\u002Fphp-proxy-guzzle-laravel-scraping","\u002Fes\u002Fblog\u002Fphp-proxy-guzzle-laravel-guia-completa","\u002Ffr\u002Fblog\u002Fguide-proxy-php-guzzle-laravel","\u002Fde\u002Fblog\u002Fphp-http-proxy-leitfaden","\u002Ftr\u002Fblog\u002Fphp-http-proxy-kullanimi-rehberi","\u002Fpt\u002Fblog\u002Fguia-proxy-http-php-curl-guzzle-laravel","\u002Fcn\u002Fblog\u002Fphp-http-proxy-guzzle-laravel-guide-1","\u002Fja\u002Fblog\u002Fphp-http-proxy-guide-2026","\u002Fit\u002Fblog\u002Fguida-proxy-http-php-curl-guzzle-laravel",165,[71,105,132,149],{"id":72,"slug":73,"title":74,"excerpt":75,"featured_image_url":76,"featured_image_alt":77,"card_image_url":78,"og_image_url":79,"published_at":80,"updated_at":81,"content_updated_at":82,"reading_time_minutes":83,"is_featured":40,"indexable":4,"views":84,"author":85,"categories":86,"tags":88},210,"nastrojka-proksi-dlya-ai-agentov","Прокси для AI-агентов: browser-use, Crawl4AI и MCP-сервер","Агенты на облачных виртуалках выходят в сеть с IP дата-центров. Даём актуальную рабочую настройку прокси для browser-use, Crawl4AI и MCP-сервера, таблицу выбора между sticky и ротацией и разбираем ловушки, на которых сгорает бюджет.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fnastrojka-proksi-dlya-ai-agentov-master.webp","Proxy Setup for AI Agents: browser-use, Crawl4AI and an MCP Server","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fnastrojka-proksi-dlya-ai-agentov-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fnastrojka-proksi-dlya-ai-agentov-og.webp","2026-10-24T09:00:00+00:00","2026-10-24T09:00:20+00:00","2026-10-03T09:41:40+00:00",14,34,{"name":45,"slug":46,"bio":47,"avatar_url":14,"website_url":14,"social_links":14},[87],{"id":50,"slug":51,"name":52,"description":14,"meta_title":53,"meta_description":54,"parent_id":14},[89,93,97,101],{"id":90,"slug":91,"name":92},1,"veb-skraping","Веб-скрапинг",{"id":94,"slug":95,"name":96},2,"rezidentskie-proksi","Резидентские прокси",{"id":98,"slug":99,"name":100},9,"python","Python",{"id":102,"slug":103,"name":104},22,"playwright","Playwright",{"id":106,"slug":107,"title":108,"excerpt":109,"featured_image_url":110,"featured_image_alt":111,"card_image_url":112,"og_image_url":113,"published_at":114,"updated_at":115,"content_updated_at":82,"reading_time_minutes":83,"is_featured":40,"indexable":4,"views":116,"author":117,"categories":118,"tags":120},206,"camoufox-rezidentnye-proksi-python","Camoufox с резидентными прокси: практическое руководство на Python","Как запустить Camoufox — Firefox с патчами на C++ — за резидентными прокси: актуальный Python API, почему geoip нужна sticky-сессия, чек-лист согласованности отпечатка и когда лучше подойдут Patchright или nodriver.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fcamoufox-rezidentnye-proksi-python-master.webp","Camoufox with Residential Proxies: A Code-First Python Guide","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fcamoufox-rezidentnye-proksi-python-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fcamoufox-rezidentnye-proksi-python-og.webp","2026-10-13T09:00:00+00:00","2026-10-13T09:00:22+00:00",45,{"name":45,"slug":46,"bio":47,"avatar_url":14,"website_url":14,"social_links":14},[119],{"id":50,"slug":51,"name":52,"description":14,"meta_title":53,"meta_description":54,"parent_id":14},[121,122,123,127,128],{"id":90,"slug":91,"name":92},{"id":94,"slug":95,"name":96},{"id":124,"slug":125,"name":126},6,"anti-obnaruzhenie","Анти-обнаружение",{"id":98,"slug":99,"name":100},{"id":129,"slug":130,"name":131},21,"bezgolovnyj-brauzer","Headless-браузер",{"id":133,"slug":134,"title":135,"excerpt":136,"featured_image_url":137,"featured_image_alt":138,"card_image_url":139,"og_image_url":140,"published_at":141,"updated_at":141,"content_updated_at":142,"reading_time_minutes":143,"is_featured":40,"indexable":4,"views":144,"author":145,"categories":146,"tags":148},176,"got-scraping-nodejs-residential-proxies","got-scraping в Node.js: руководство по парсингу с резидентными прокси","Практическое руководство для Node.js-разработчиков: как использовать got-scraping с генератором заголовков, HTTP\u002F2 и резидентными прокси ProxyHat для масштабного парсинга без блокировок.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fgot-scraping-nodejs-residential-proxies-master.webp","got-scraping in Node.js: A Developer's Guide with Residential Proxies","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fgot-scraping-nodejs-residential-proxies-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Fgot-scraping-nodejs-residential-proxies-og.webp","2026-08-04T16:05:06+00:00","2026-10-03T08:29:58+00:00",12,130,{"name":45,"slug":46,"bio":47,"avatar_url":14,"website_url":14,"social_links":14},[147],{"id":50,"slug":51,"name":52,"description":14,"meta_title":53,"meta_description":54,"parent_id":14},[],{"id":150,"slug":151,"title":152,"excerpt":153,"featured_image_url":154,"featured_image_alt":155,"card_image_url":156,"og_image_url":157,"published_at":158,"updated_at":158,"content_updated_at":159,"reading_time_minutes":143,"is_featured":40,"indexable":40,"views":160,"author":161,"categories":162,"tags":164},175,"rotaciya-proksi-v-colly-1","Ротация прокси в Colly: Полное руководство для Go-разработчиков","Практическое руководство по ротации прокси в Colly — от встроенного RoundRobinProxySwitcher до кастомных SetProxyFunc с резидентными IP. Примеры кода, продакшн-паттерны и типичные ошибки.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Frotaciya-proksi-v-colly-1-master.webp","Rotating Proxies in Colly: A Framework-Idiomatic Guide for Go Developers","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Frotaciya-proksi-v-colly-1-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog-covers\u002Fru\u002Frotaciya-proksi-v-colly-1-og.webp","2026-08-04T10:05:34+00:00","2026-10-03T08:29:56+00:00",81,{"name":45,"slug":46,"bio":47,"avatar_url":14,"website_url":14,"social_links":14},[163],{"id":50,"slug":51,"name":52,"description":14,"meta_title":53,"meta_description":54,"parent_id":14},[],[]]