Reputation: 1852
I use the following code to check the file size of a external pdf. But I want to add a timeout and skip if the external server does not respond within 1 second. How can I achieve this?
My current code:
<?php
$newmanual = "https://www.example.com/file.pdf"
$head = array_change_key_case(get_headers($newmanual, TRUE));
$filesize = $head['content-length'];?>
Upvotes: 2
Views: 163
Reputation: 3093
Curl has a timeout function, you could use that to get the headers.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/file.pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
// The maximum number of seconds to allow cURL functions to execute.
curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds
$output = curl_exec($ch);
// close handle
curl_close($ch);
$headers = [];
$data = explode("\n",$output);
$headers['status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle=explode(":",$part);
$headers[trim($middle[0])] = trim($middle[1]);
}
echo "<pre>";
var_dumo(headers);
Code taken from posts how to set curl timeout and get header from php curl
Upvotes: 0