Jump to content

  •  

  • iBotModz CBox


    Photo

    Beginning PHP - Lesson 16 - Reading External Files into PHP


    This topic has been archived. This means that you cannot reply to this topic.
    No replies to this topic

    #1 fattwam

    fattwam

      General Grade 2

    • Sub-Admins

    • 3,979 posts
    • Joined: 18-August 07

    Posted 27 March 2008 - 08:23 PM

    Now it's time for us to learn how to use PHP's file API to create, edit, and destroy files through PHP.

    "One of the most basic things you can do with any programming language is create and manipulate data structures. These structures may be transient - in-memory variables like arrays or objects - or more permanent - disk-based entities like files or database tables; however, the ability to create, modify and erase them in a convenient and consistent manner is of paramount importance to any programmer.

    Like all widely used programming languages, PHP has the very useful ability to read data from, and write data to, files on the system. But the language doesn't just stop there - PHP comes with a full-featured file-and-directory-manipulation API that allows you (among other things) to view and modify file attributes, read and list directory contents, alter file permissions, retrieve file contents into a variety of native data structures, and search for files based on specific patterns. This file manipulation API is both powerful and flexible - two characteristics that will endear it to any developer who's ever had to work with file manipulation commands." -Melonfire



    fread
    Start by making a file in the same folder as your php scripts. Name the file "file.txt" and write something in it like:
    If you can read this my script works!
    Or maybe it doesn't...
    That's it!
    he computer is just guessing what is in the file...

    (Note: It is important that you type at least 4 lines worth of text.)
    Then close the file and make a new file named "fileopen.php" and type this into it:




    // Store the file name in a string.
    $filename = "file.txt";

    // Open the file.
    $filehandle = fopen($filename, "r");

    // Read the files contents.
    $contents = fread($filehandle, filesize($filename));

    // Close file.
    fclose($filehandle);

    // Echo the files contents
    echo $contents;

    ?>



    When you run the script you will see a blank screen with the text "If you can read this my script works!" on it. If you get an error double check your code and make sure that "file.txt" and "fileopen.php" are in the same place.

    Now to explain what the script does:



    // Store the file name in a string.
    $filename = "file.txt";


    Here we start by putting the name of the file we want in a string.




    // Open the file.
    $filehandle = fopen($filename, "r");


    Next we create a "file handle" which is kind of hard to explain, but basically it is how the computer now can remember the file. It is a "handle" that can be used to tell the computer what your referring too. I'm sure you've herd the saying "What's your Handle?" in street/gangster movies. I'm sure your probably wondering what the "r" means, it is the type of mode to open the file in - "READ" mode. For all modes see the bottom of the page.



    // Read the files contents.
    $contents = fread($filehandle, filesize($filename));


    Here we read (fread) the contents of the file into a string. Notice that there are two different parts to fread(). The first is the handle we will use to tell the script what file we want to open. The next is the number of bytes to be read. You could put a number like this:



    // Read the files contents.
    $contents = fread($filehandle, 4068);


    Where the script will stop reading the file when it gets to 4068 bytes or the end of the script. (Which ever comes first)

    However I find it easier to just tell the script to get as many bytes as there are:


    filesize($filename)







    // Close file.
    fclose($filehandle);

    // Echo the files contents
    echo $contents;


    Last we close the file and destroy the file handle. Then print the files contents to the screen. You don't have to close the file handle, but your scripts will end up with a lot of open files if you don't...


    readfile

    The simplest way to read a file into php and output it to the screen is to use the readfile() function.




    // Store the file name in a string.
    $filename = "file.txt";

    // Prints the files contents.
    readfile($filename);

    ?>









    fgets
    Here is another way to open a file and get the contents. "fgets" gets one line out of the file specified by the file handle.




    // Store the file name in a string.
    $filename = "file.txt";

    // Open the file.
    $filehandle = fopen($filename, "r");

    // Read the file line by line into a string.
    while (!feof($filehandle))
    {
    $contents .= fgets($filehandle);
    }

    // Close file.
    fclose($filehandle);

    // Echo the files contents
    echo $contents;

    ?>



    The first part specifies the file to open and creates a "handle" for it:


    // Store the file name in a string.
    $filename = "file.txt";

    // Open the file.
    $filehandle = fopen($filename, "r");



    Next we need to recal that lesson about loops to understand the "while" loop:


    // Read the file line by line into a string.
    while (!feof($$filehandle))
    {
    $contents .= fgets($fh);
    }


    Basicaly, in human language it says:
    While it is not the END OF THE FILE (feof: FILE END OF) {
    	Get a line out of the file and add it to the string $contents. 
    	($contents .= fgets($fh))
    }
    Note: the little dot in front of the "=" sign means "add to". If the code was:


    $contents = fgets($fh);


    Then every time the while loop ran it would over write the old value of $contents with a new value. But we don't want it to do that! We want it to add the new value to $contents.


    File()

    Last I want to show you how to read a file into an array! If you haven't read the lesson on arrays you need to do so now! (I also recommend that you open "file.txt" and change the text because it is getting old....)




    // Store the file name in a string.
    $filename = "file.txt";

    // Read file into array
    $contents = file($filename);

    // Loop through the array and print each line to the screen.
    foreach ($contents as $line)
    {
    echo $line;
    }

    ?>


    Ok, this one is the hardest, but don't worry we'll get it down!
    In English the foreach loop looks like this:
    For every element/line in the array "$contents": put that element into a variable called "$line" {
    	Then print the value of "$line" to the screen.
    }


    Hope this lesson helped you to understand how to read files into PHP Scripts Next lesson I will show you how to do more advanced things with files!


    MODES

    Here are all of the modes for the fopen() function:


    mode Description
    'r' Open for reading only; place the file pointer at the beginning of the file.
    'r+' Open for reading and writing; place the file pointer at the beginning of the file.
    'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.
    'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.


    Taken from the PHP Manual