<?php

$down = (!empty($_GET['down']) ? (int)$_GET['down'] : mt_rand(1000, 5000)) * 1000;
$up = (!empty($_GET['up']) ? (int)$_GET['down'] : mt_rand(1000, 5000)) * 1000;
$ping = !empty($_GET['ping']) ? (int)$_GET['ping'] : mt_rand(0, 20);
$server = !empty($_GET['server']) ? (int)$_GET['server'] : 6601; // https://c.speedtest.net/speedtest-servers-static.php
$accuracy = 8;

$headers = [
    'POST /api/api.php HTTP/1.1',
    'Host: www.speedtest.net',
    'User-Agent: Speedtest',
    'Content-Type: application/x-www-form-urlencoded',
    'Origin: https://www.speedtest.net',
    'Referer: https://www.speedtest.net',
    'Connection: Close'
];

$postData = [
    'startmode' => 'recommendedselect',
    'recommendedserverid' => $server,
    'serverid' => $server,
    'promo' => '',
    'upload' => $up,
    'download' => $down,
    'ping' => $ping,
    'accuracy' => $accuracy,
    'hash' => md5("$ping-$up-$down-297aae72")
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.speedtest.net/api/api.php');
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
$data = curl_exec($ch);
curl_close($ch);

foreach (explode('&', $data) as $chunk) {
    $params = explode("=", $chunk);

    if (urldecode($params[0]) === 'resultid') {
        die(
            '<a href="https://speedtest.net/result/' . urldecode(
                $params[1]
            ) . '"><img src="' . 'https://speedtest.net/result/' . urldecode($params[1]) . '.png" alt=""/></a>'
        );
    }
}