V
V
Valery Efremov2015-08-27 22:27:39
PHP
Valery Efremov, 2015-08-27 22:27:39

PHP. VK JSON. How to reconnect if timeout?

Good day, colleagues!
Used php file_get_contents() to get JSON from VK. But I manage to get an answer every other time (either restrictions on the IP of my server, or the workload of the VK API).
PHP Warning: file_get_contents(vk.com/...): failed to open stream: Connection timed out in
Essence of the question: let's say VK did not give any data for 2-3 seconds, how to reconnect until it will give JSON?
If file_get_contents is not suitable for this, then maybe use curl (although I don’t know it at all)?
Thanks in advance :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaliy Orlov, 2015-08-27
@WebAir

$ctx = stream_context_create(['http'=>['timeout'=>3]]); // таймаут в секундах
$maxAttempts = 2;  // макс кол-во попыток
$attempt = 0; // тут будет храниться кол-во совершенных попыток 
while(!($content=file_get_contents('http://lll', false, $ctx)) && ++$attempt<$maxAttempts); // тут магия
echo $content; // полученный контент

or as curl was written above, there are a lot of manuals for it in Google

V
Valery Efremov, 2015-08-27
@WebAir

What do you say about the account?

do {
$ctx = stream_context_create(array('http'=>
array(
'timeout' => 3,  //максимум 3 сек
)
));
$getcontents = @file_get_contents("vkurl", false, $ctx); // выбивает ошибку таймаута по прошествии 3-х секунд, вывод ошибки отключаем
} while ($getcontents===false); //зацикливаем до тех пор, пока не получим что нибудь ценное ))
echo $getcontents;

or else here
while($content = @file_get_contents('vkurl')){echo $content;}

V
Vlad Pasechnik, 2015-08-28
@jumper423

Most methods are limited to no more than 3 requests per second, other methods may have even more stringent restrictions. This is already not disclosed by VK.
If you are doing this in a loop, then just add

sleep(2);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question