Get an API key Your API keys

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:

Shell
export VP_KEY="vp_live_…"

The client

vp.php
<?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

See Limits and retries for the reasoning and Errors for every code.

Keep one IP for several requests

PHP
$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 minutes

Images, PDFs and other files

PHP
$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