VirginProxy with PHP
A complete, copy-ready client for VirginProxy in PHP (8.0 or newer): one function that sends a request, retries what is worth retrying, and returns the answer with its price. It uses nothing but the standard HTTP library.
Set your key as an environment variable first:
export VP_KEY="vp_live_…"The client
<?php
// vp.php: needs the curl and json extensions
const VP_API = 'https://api.virginproxy.com/v1/requests';
const VP_RETRYABLE = ['rate_limited', 'concurrency_limited', 'busy', 'maintenance',
'timeout', 'target_unreachable', 'connection_failed'];
function vp_fetch(string $url, array $options = [], int $retries = 3): array
{
for ($attempt = 0; ; $attempt++) {
$ch = curl_init(VP_API);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 180,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('VP_KEY'), 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode(['url' => $url] + $options),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$data = json_decode((string) $body, true) ?? ['error' => ['code' => 'network', 'message' => 'no answer']];
if ($status === 200) {
return $data;
}
$error = $data['error'];
if (!in_array($error['code'], VP_RETRYABLE, true) || $attempt === $retries) {
throw new RuntimeException($error['code'] . ': ' . $error['message']);
}
usleep(($error['retry_after_ms'] ?? 1000 * 2 ** $attempt) * 1000);
}
}
$page = vp_fetch('https://httpbin.org/html');
echo $page['status'], ' ', $page['exit']['ip'], ' ', $page['cost']['credits'], PHP_EOL;What the client does
- Sends one
POST /v1/requestsper call and waits up to 180 seconds: enough for your plan's timeout, the wait for a free slot and afresh_ip. Withretry, allow one more timeout per extra attempt. - Retries only errors that can succeed later (
rate_limited,concurrency_limited,busy,maintenance,timeout,target_unreachable,connection_failed), waitingretry_after_mswhen the API sends it. None of these is charged. - Raises every other error at once: a wrong URL or key does not get better by trying again.
See Limits and retries for the reasoning and Errors for every code.
Keep one IP for several requests
$first = vp_fetch('https://shop.example/cart', ['session' => 'cart-42']);
$second = vp_fetch('https://shop.example/checkout', ['session' => 'cart-42']);
var_dump($first['exit']['ip'] === $second['exit']['ip']); // true for up to 10 minutesImages, PDFs and other files
$data = vp_fetch('https://httpbin.org/image/png');
$raw = $data['body_encoding'] === 'base64' ? base64_decode($data['body']) : $data['body'];
file_put_contents('image.png', $raw);Was this page helpful?
Last updated