Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Stop script file_get_contents() after 2 seconds

Tags:

php

Okay so I have a PHP script that loads another page using file_get_contents().

The other page takes around 30 seconds to load (the type of script it is), and all I need is the file_get_contents() is to initiate this script.

The problem is, the file_get_contents() will stay loading for the whole 30 seconds. The only way to stop this is to close the tab (when closing the tab the script it calls still runs).

So, how can I get it so the file_get_contents(); closes after say 2 seconds?

Thanks in advance

like image 374
Anim8r Avatar asked Oct 04 '22 06:10

Anim8r


2 Answers

Can't answer your question but I recommend using cURL instead file_get_contents.

Example:

function get_url_contents($url) {
    $crl = curl_init();

    curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
    curl_setopt($crl, CURLOPT_URL, $url);
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);

    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}

Your issue may be from the timeout: default_socket_timeout

But this doesn't seem logically because 2 seconds is really very few and I can't explain myself why someone would change it to 2 seconds. The default is 60 seconds.

like image 154
enenen Avatar answered Oct 13 '22 10:10

enenen


In the manual page we can see that file_get_contents() accepts a third argument called $context were we are able to fine-tune our options. Following some links from there we reach HTTP context options where timeout appears to be our man:

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout setting is used.

So you can either provide a context or change default_socket_timeout (first option looks less prone to break other things).

Disclaimer: I haven't tested it.

like image 24
Álvaro González Avatar answered Oct 13 '22 10:10

Álvaro González