Liam Bailey
Liam Bailey

Reputation: 5905

Check when file_get_contents is finished

Is there anyway I can check when file_get_contents has finished loading the file, so I can load another file, will it automatically finish loading the one file before going onto the next one?

Upvotes: 4

Views: 6903

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

simple example that will loop through and get google.co.uk#q=* 5 times and output if it got it or not, pretty useless but kinda answers your question that a check can be done to see if file_get_contents was successful before doing the next one, obviously google could be changed to something else. but wouldn't be very practical. plus output buffering dont output within functions.

<?php 
function _flush (){
    echo(str_repeat("\n\n",256));
    if (ob_get_length()){           
        @ob_flush();
        @flush();
        @ob_end_flush();
    }   
    @ob_start();
}
function get_file($loc){
    return file_get_contents($loc);
}

for($i=0;$i<=5;$i++){

    $content[$i] = @get_file("http://www.google.co.uk/#q=".$i);
    if($content[$i]===FALSE){
        echo'Error getting google ('.$i.')<br>';
            return;
    }else{
        echo'Got google ('.$i.')<br>';
    }
    ob_flush();
    _flush();
}
?>

Upvotes: 1

Rob Agar
Rob Agar

Reputation: 12459

PHP is single threaded - all functions happen one after the other. There is a php_threading PECL extension if you did want to try loading files asynchronously, but I haven't tried it myself so I can't say if it would work or not.

Upvotes: 2

mario
mario

Reputation: 145482

Loading a file with file_get_contents() will block operation of your script until PHP is finished reading it in completely. It must, because you couldn't assign the $content = otherwise.

Upvotes: 23

Related Questions