5

I'm trying to do a variation of file_get_content BUT without waiting for the content. Basically I'm requesting a another php script in different url that will download a large file, so I don't want to wait for the file to finish loading. Anyone has any idea?

Thank you!

Patrick
  • 4,815
  • 11
  • 52
  • 55

3 Answers3

2

I would suggest checking out either the popen function or the curl multi functions.

The simplest way would be to do:

$fh = popen("php /path/to/my/script.php");

// Do other stuff

// Wait for script to finish
while (fgets($fh) !== false) {}

// Close the file handle
pclose($fh);

If you don't want to wait for it to finish at all:

exec("php /path/to/my/script.php >> /dev/null &");

or

exec("wget http//www.example.com/myscript.php");
Horatio Alderaan
  • 3,264
  • 2
  • 24
  • 30
  • I was using wget variant but it is quite resource hungry. It can easily take up to 0.1 s and more to process, which is quite bad if you need to do it periodically on exposed web pages. – Josef Sábl Jun 28 '11 at 13:24
2

Try this on the script that will download that file:

//Erase the output buffer
ob_end_clean();
//Tell the browser that the connection's closed
header("Connection: close");

//Ignore the user's abort.
ignore_user_abort(true);

//Extend time limit to 30 minutes
set_time_limit(1800);
//Extend memory limit to 10MB
ini_set("memory_limit","10M");
//Start output buffering again
ob_start();

//Tell the browser we're serious... there's really
//nothing else to receive from this page.
header("Content-Length: 0");

//Send the output buffer and turn output buffering off.
ob_end_flush();
//Yes... flush again.
flush();

//Close the session.
session_write_close();

// Download script goes here !!!

stolen from: http://andrewensley.com/2009/06/php-redirect-and-continue-without-abort/

s3v3n
  • 8,203
  • 5
  • 42
  • 56
  • You'd want to do session_write_close() as close to the start of the script as possible, or this script will lock the session until the download's completed, even if the user's aborted on their end. – Marc B Dec 18 '10 at 01:59
  • This code should be the first in file. All the rest (the download script and so on) should be after it. In this example that place is marked as `// Download script goes here` – s3v3n Dec 18 '10 at 02:02
  • 1
    Good answer for the particular problem in question, but does not solve the question itself. I need something similar, but I don't have the second script under my control so this does not work for me. – Josef Sábl Jun 28 '11 at 13:20
1

I successfully used curl_post_async from this thread.

How do I make an asynchronous GET request in PHP?

Community
  • 1
  • 1
Josef Sábl
  • 7,538
  • 9
  • 54
  • 66