### Get Available Proxy using getProxy() and Handle Exceptions (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Shows how to retrieve an available proxy server using the `getProxy()` method. It includes handling the `ProxiesEndedException` which is thrown when no proxies are available. The example also demonstrates how to get the proxy address and how to increment failed attempts if an HTTP request fails. ```php getProxy(); // Получение адреса для использования в HTTP-клиенте $proxyAddress = $proxy->getAddress(); // Результат: "1.1.1.1:80" // Использование прокси для HTTP-запроса $ch = curl_init('http://example.com'); curl_setopt($ch, CURLOPT_PROXY, $proxyAddress); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); // Если запрос неудачный — фиксируем ошибку if ($response === false) { $proxy->increaseFailedAttemptsCount(); } curl_close($ch); } catch (ProxiesEndedException $e) { echo 'Нет доступных прокси-серверов'; } ``` -------------------------------- ### Install Proxy Manager Bundle via Composer Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt This snippet shows how to install the Proxy Manager Bundle using Composer, the dependency manager for PHP. It specifies the package name and the desired version. ```bash composer require "cosmologist/proxy-manager-bundle" "dev-master" ``` -------------------------------- ### Asynchronous Downloading with Guzzle and Proxy Manager (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt An example of integrating Guzzle with the Proxy Manager Bundle for asynchronous downloads. It covers setting proxies before requests, handling successful responses, and managing errors by increasing failed attempt counts. ```php function (BeforeEvent $event) use ($proxyManager) { $proxy = $proxyManager->getProxy()->getAddress(); $event->getRequest()->getConfig()->set('proxy', $proxy); echo sprintf("Прокси %s для %s\n", $proxy, $event->getRequest()->getUrl()); }, // Обработка успешных запросов 'complete' => function (CompleteEvent $event) { echo 'Завершён: ' . $event->getRequest()->getUrl() . "\n"; $html = $event->getResponse()->getBody(); // Обработка полученных данных... }, // Обработка ошибок с пометкой неудачной попытки 'error' => function (ErrorEvent $event) use ($proxyManager) { $proxyAddress = $event->getRequest()->getConfig()->get('proxy'); $proxy = $proxyManager->findProxyByAddress($proxyAddress); if ($proxy) { $proxy->increaseFailedAttemptsCount(); } echo sprintf("Ошибка: %s через %s\n", $event->getRequest()->getUrl(), $proxyAddress); }, // Размер пула одновременных запросов 'pool_size' => 50 ]; // Формирование списка запросов $requests = [ $guzzle->createRequest('GET', 'http://example.com/page1.html', ['timeout' => 20]), $guzzle->createRequest('GET', 'http://example.com/page2.html', ['timeout' => 20]), $guzzle->createRequest('GET', 'http://example.com/page3.html', ['timeout' => 20]), ]; // Запуск асинхронного скачивания Pool::batch($guzzle, $requests, $options); ``` -------------------------------- ### Get Proxy Address using getAddress() (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Illustrates how to retrieve the address of a proxy server in the standard 'host:port' format using the `getAddress()` method of a `Proxy` object. This address can then be used with HTTP clients like Guzzle. ```php getProxy(); // Получение адреса прокси $address = $proxy->getAddress(); // Результат: "proxy.example.com:8080" // Использование в Guzzle $client = new GuzzleHttp\Client([ 'proxy' => $address ]); ``` -------------------------------- ### Manage Proxy Last Access Timestamp (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Provides methods to get and set the timestamp of the last proxy usage. These are used by the manager to enforce minimum intervals between proxy requests. ```php getProxy(); // Получение времени последнего использования $lastAccess = $proxy->getLastAccessTimestamp(); echo 'Последнее использование: ' . date('Y-m-d H:i:s', $lastAccess); // Ручная установка времени (обычно не требуется) $proxy->setLastAccessTimestamp(time()); ``` -------------------------------- ### Get Failed Proxy Attempts Count (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Retrieves the current count of failed proxy usage attempts for monitoring proxy status. This method is useful for understanding proxy reliability. ```php findProxyByAddress($address); if ($proxy) { echo sprintf( "Прокси %s: %d неудачных попыток\n", $proxy->getAddress(), $proxy->getFailedAttemptsCount() ); } } ``` -------------------------------- ### Create Proxy Manager Instance (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Demonstrates how to create an instance of the Manager class from the Proxy Manager Bundle. It shows how to pass the list of proxy servers, the minimum access period between proxy uses, and the maximum number of failed attempts before a proxy is excluded. ```php proxyManager = $this->getContainer()->get('cosmologist.proxy_manager'); // $this->proxyManager->setProxies($proxies); // $this->proxyManager->setMinAccessPeriod($minAccessPeriod); // $this->proxyManager->setMaxFailedAccessCount($maxFailedAccessCount); try { $proxy = $proxyManager->getProxy(); // Получаем адрес прокси-сервера $proxyAddress = $proxy->getAddress(); // Что-то делаем через прокси, к примеру, скачиваем страницу ... // Если результат скачивания неудачный, фиксируем, что для данного прокси была неудачная попытка $proxy->increaseFailedAttemptsCount(); } catch (ProxiesEndedException $e) { echo 'Нет доступных для использования прокси-серверов'; } ``` -------------------------------- ### Dynamically Set Proxies using setProxies() (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Illustrates how to use the `setProxies()` method to dynamically update the list of proxy servers in a Manager instance after it has been created. This allows for adding or replacing proxies during runtime. ```php setProxies([ '192.168.1.1:8080', '192.168.1.2:8080', '192.168.1.3:3128' ]); ``` -------------------------------- ### Symfony Bundle Configuration and Usage (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Shows how to configure and use the Proxy Manager Bundle within a Symfony application. It demonstrates retrieving the service from the container and setting proxies. ```php get('cosmologist.proxy_manager'); // Настройка параметров $proxyManager->setProxies([ '1.1.1.1:80', '2.2.2.2:8080' ]); try { $proxy = $proxyManager->getProxy(); // Использование прокси... } catch (ProxiesEndedException $e) { return $this->json(['error' => 'Нет доступных прокси']); } } } ``` -------------------------------- ### Handle ProxiesEndedException (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Demonstrates how to catch the ProxiesEndedException, which is thrown when all proxies are unavailable (either busy or have exceeded their failed attempt limit). It suggests waiting before retrying. ```php getProxy(); // Успешно $proxy2 = $proxyManager->getProxy(); // ProxiesEndedException - нужно ждать 60 секунд } catch (ProxiesEndedException $e) { echo 'Все прокси заняты, повторите позже'; sleep(60); } ``` -------------------------------- ### Find Proxy by Address using findProxyByAddress() (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Demonstrates the `findProxyByAddress()` method, which allows searching for a specific `Proxy` object within the manager using its address. This is useful for updating proxy statistics, such as failed attempts, from callback functions. ```php findProxyByAddress('1.1.1.1:80'); if ($proxy !== null) { echo 'Прокси найден: ' . $proxy->getAddress(); echo 'Неудачных попыток: ' . $proxy->getFailedAttemptsCount(); } else { echo 'Прокси не найден'; } ``` -------------------------------- ### Increase Failed Attempts Count using increaseFailedAttemptsCount() (PHP) Source: https://context7.com/cosmologist/proxymanagerbundle/llms.txt Shows how to use the `increaseFailedAttemptsCount()` method on a `Proxy` object. This method increments the counter for failed attempts. After reaching the maximum configured failed attempts, the proxy is automatically removed from the rotation. ```php getProxy(); // Симуляция HTTP-запроса $success = false; // предположим, что запрос неудачный if (!$success) { // Увеличиваем счётчик неудачных попыток $proxy->increaseFailedAttemptsCount(); echo 'Неудачных попыток: ' . $proxy->getFailedAttemptsCount(); // После 3 неудач прокси будет исключён из ротации } ``` -------------------------------- ### PHP: Multithreaded Downloading with Guzzle and ProxyManagerBundle Source: https://github.com/cosmologist/proxymanagerbundle/blob/master/README.md Illustrates how to use ProxyManagerBundle in conjunction with Guzzle for multithreaded web scraping. It configures Guzzle's request pool to use proxies managed by ProxyManagerBundle, handling proxy assignment before requests, parsing responses upon completion, and marking proxies as failed on error. ```php function (BeforeEvent $event) use ($proxyManager) { $proxy = $proxyManager->getProxy()->getAddress(); $event->getRequest()->getConfig()->set('proxy', $proxy); echo sprintf("Set proxy %s for %s\n", $proxy, $event->getRequest()->getUrl()); }, 'complete' => function (CompleteEvent $event) use ($that) { echo 'Completed request to ' . $event->getRequest()->getUrl() . "\n"; $that->parsePage($event->getResponse()); }, 'error' => function (ErrorEvent $event) use ($proxyManager) { $proxyAddress = $event->getRequest()->getConfig()->get('proxy'); if ($proxy = $proxyManager->findProxyByAddress($proxyAddress)) { $proxy->increaseFailedAttemptsCount(); } echo sprintf("Request failed to %s with proxy %s\n", $event->getRequest()->getUrl(), $proxyAddress); }, 'pool_size' => 100 ]; // Формируем набор HTTP-запросов $requests = [ $guzzle->createRequest('GET', 'http://example.com/first.html', ['connect_timeout' => 10, 'timeout' => 20]), $guzzle->createRequest('GET', 'http://example.com/second.html', ['connect_timeout' => 10, 'timeout' => 20]), ... $guzzle->createRequest('GET', 'http://example.com/last.html', ['connect_timeout' => 10, 'timeout' => 20]) ]; // Запускаем асинхронное скачивание Pool::batch($guzzle, $requests, $options); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.