|
<?php |
|
|
|
// PLEASE: DO NOT ATTEMPT WITH YOUR STARTER KEY!!! |
|
// You will blow your daily limit. Trust me. Pls. |
|
$apiKey = 'your API key'; |
|
|
|
$repeat = 'cli' === PHP_SAPI |
|
? ($argv[1] ?? 20) |
|
: ($_GET['repeat'] ?? $_GET['n'] ?? $_GET['r'] ?? 20); |
|
|
|
function runCurl(string $url, string $method = 'GET', array $payload = []): float |
|
{ |
|
global $apiKey; |
|
$start = microtime(true); |
|
|
|
$curl = curl_init(); |
|
|
|
$options = [ |
|
CURLOPT_URL => $url, |
|
CURLOPT_RETURNTRANSFER => true, |
|
CURLOPT_ENCODING => '', |
|
CURLOPT_MAXREDIRS => 5, |
|
CURLOPT_TIMEOUT => 30, |
|
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, |
|
CURLOPT_CUSTOMREQUEST => 'GET', |
|
CURLOPT_HTTPHEADER => [ |
|
'Key:'.$apiKey, |
|
], |
|
]; |
|
|
|
if ('POST' === $method) { |
|
$options[CURLOPT_HTTPHEADER][] = 'Content-Type:application/x-www-form-urlencoded'; |
|
$options[CURLOPT_POSTFIELDS] = http_build_query($payload); |
|
$options[CURLOPT_CUSTOMREQUEST] = 'POST'; |
|
} |
|
|
|
curl_setopt_array($curl, $options); |
|
|
|
$rawResponse = curl_exec($curl); |
|
curl_close($curl); |
|
|
|
return microtime(true) - $start; |
|
} |
|
|
|
function runGetContents(string $url, string $method = 'GET', array $payload = []): float |
|
{ |
|
global $apiKey; |
|
$start = microtime(true); |
|
|
|
$options = [ |
|
'max_redirects' => 5, |
|
'timeout' => 30, |
|
'protocol_version' => 1.1, |
|
'method' => 'GET', |
|
'header' => "Key:{$apiKey}\r\n", |
|
]; |
|
|
|
if ('POST' === $method) { |
|
$options['header'] .= "Content-Type:application/x-www-form-urlencoded\r\n"; |
|
$options['content'] = http_build_query($payload); |
|
$options['method'] = 'POST'; |
|
} |
|
|
|
$context = stream_context_create(['http' => $options]); |
|
|
|
file_get_contents($url, false, $context); |
|
|
|
return microtime(true) - $start; |
|
} |
|
|
|
$dataset = [ |
|
'get_provinces' => ['https://api.rajaongkir.com/starter/province'], |
|
'get_cities_by_province' => ['https://api.rajaongkir.com/starter/city?province=6'], |
|
'get_cost' => ['https://api.rajaongkir.com/starter/cost', 'POST', [ |
|
'origin' => 501, |
|
'destination' => 80, |
|
'weight' => 1000, |
|
'courier' => 'jne', |
|
]], |
|
]; |
|
|
|
$result = []; |
|
|
|
if ('cli' !== PHP_SAPI) { |
|
header('Content-Type: text/plain'); |
|
} |
|
|
|
echo 'PHP version: '.PHP_VERSION."\nSAPI: ".PHP_SAPI."\n\n"; |
|
|
|
foreach ($dataset as $title => $data) { |
|
echo "Run: {$title}\n"; |
|
for($i = 1; $i <= $repeat; $i++) { |
|
echo "#{$i}... "; |
|
$result['curl'][$title][] = runCurl(...$data); |
|
$result['file_get_contents'][$title][] = runGetContents(...$data); |
|
echo "Done\n"; |
|
} |
|
echo "\n"; |
|
} |
|
|
|
$render = json_encode($result, JSON_PRETTY_PRINT)."\n"; |
|
|
|
file_put_contents(__DIR__.'/result-'.PHP_VERSION.('cli'===PHP_SAPI?'-cli':'-nginx-unixsock').'.json', $render); |
|
|
|
if ('cli'!==PHP_SAPI) { |
|
echo $render; |
|
} |
|
|
|
echo "\n\n"; |