2

Panique did a great job answering a question on this thread: PHP directory list from remote server

But he created a function I don't understand at all and was hoping to get some sort of explanation. For example, what's with the random 8192 number?

function get_text($filename) {

    $fp_load = fopen("$filename", "rb");

    if ( $fp_load ) {

            while ( !feof($fp_load) ) {
                $content .= fgets($fp_load, 8192);
            }

            fclose($fp_load);

            return $content;

    }
}
Community
  • 1
  • 1
Xtremefaith
  • 907
  • 1
  • 9
  • 29

3 Answers3

1

It loads the file which path is in $filename and returns it's content. 8192 is not random. it means read the file in chunks of 8kb.

The while loop runs as long as the file wasn't entirely read. Each iteration adds the latest 8kb of the file to $content which is returned at the end of the function.

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
0

It loads a file's data.

For example, what's with the random 8192 number?

http://php.net/manual/en/function.fgets.php

Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Zevi Sternlicht
  • 5,399
  • 19
  • 31
0

To break it down:

function get_text($filename) { //Defines the function, taking one argument - Filename, a string.

    $fp_load = fopen("$filename", "rb"); //Opens the file, with "read binary" mode.

    if ( $fp_load ) { // If it's loaded - fopen() returns false on failure

            while ( !feof($fp_load) ) { //Loop through, while feof() == false- feof() is returning true when finding a End-Of-File pointer
                $content .= fgets($fp_load, 8192); // appends the following 8192 bits (or newline, or EOF.)
            } //Ends the loop - obviously.

            fclose($fp_load); //Closes the stream, to the file.

            return $content; //returns the content of the file, as appended and created in the loop. 

    } // ends if
} //ends function

I hope this helps.

To elaborate on the 8192:

Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

from: http://php.net/manual/en/function.fgets.php

Frederik Spang
  • 3,379
  • 1
  • 25
  • 43