Jump to content

  •  

  • iBotModz CBox


    Photo

    Beginning PHP - Lesson 18 - 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:25 PM

    Now that we know how to read data from files into arrays, strings, and variables, lets try writing to files. Writing to files is pretty much the same as reading from them:

    1) First you put the file name/path in a variable so that we can tell the computer what file we want edited (We can it "the file handle").
    2) Then we open the file.
    3) Now instead of reading from the file we write to the file.
    4) Finally we close the file.


    Open up you text editor (SciTE I hope) and type the following into it. When you are done, upload it to your web server.





    // 1) Store the file name in a string (this is the file handle).
    $filename = "writetest.txt";
    // 2) Open the file
    $filehandle = fopen($filename, 'w');
    // 3) Write what we want to the file
    fwrite($filehandle, "This goes in the file.n");
    // 4) Close the file
    fclose($filehandle);

    ?>

    (Note: if you don't see anything when you browse to the file, it worked. You won't see anything because we don't "echo" or "print" anything in this script; all we do is write to a file.)

    One thing you might notice is that in addition to the script writing to the file, the script also CREATED the file! The "w" command that we put in the fopen function ( fopen($filename, 'w') ) means this to the computer: "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."


    Now if you open "writetest.txt" you will see this in it:


    This goes in the file.


    And there you have it! I told you it was just as easy to write to files!

    Now lets modify the file to create five lines of text, we will put them on different lines using the "next line" (n) character:


    // Put the text we want in the file in a string.
    $text = "This is line one.nThis is line two.nThis is line three.nThis is line four.nThis is line five.n";

    // 1) Store the file name in a string (this is the file handle).
    $filename = "writetest.txt";
    // 2) Open the file
    $filehandle = fopen($filename, 'w')
    // 3) Write what we want to the file
    fwrite($filehandle, $text);
    // 4) Close the file
    fclose($filehandle);

    ?>


    Now after running the file you will see this in writetext.txt:

    This is line one.
    This is line two.
    This is line three.
    This is line four.
    This is line five.

    Peace of cake, huh? 8)


    To finish off our file lets delete the comments in the code (you can keep them if you want) and add a couple of error checking functions - just so you learn to code properly. First lets add a "die" command to the fopen function:



    $text = "This is line one.nThis is line two.nThis is line three.nThis is line four.nThis is line five.n";
    $filename = "writetest.txt";
    $filehandle = fopen($filename, 'w') or die('Could not open the file');
    fwrite($filehandle, $text);
    fclose($filehandle);
    ?>

    The or die command just means:
    If there is an error: stop the script and display this message instead of a cryptic PHP error message.
    Feel free to change "Could not open the file" to anything you want the error to say. You can test it by putting an error like this in the code:

    $filehandle = fopen($filename22222, 'w') or die('Could not open the file');



    Second lets add a message that lets us know that everything went all right. (First fix the error you just made :wink:


    $text = "This is line one.nThis is line two.nThis is line three.nThis is line four.nThis is line five.n";
    $filename = "writetest.txt";
    $filehandle = fopen($filename, 'w') or die('Could not open the file');

    if (!fwrite($filehandle, $text)) {
    echo "Could Not write to the file!";
    } else {
    echo "Wrote the following to the file:
    $text";
    }

    fclose($filehandle);
    ?>


    For those of you who don't know; this is an if statement. Lets take it line by line to make it easier to understand:


    if (!fwrite($filehandle, $text)) {
    echo "Could Not write to the file!";

    In english it reads:
    if (you [b]cannont[/b] write (!fwrite) the value of "$text" to "writetest.txt") { 
    	print "Could Not write to the file!"
    Basically, if something goes wrong and you CANNOT write to the file, tell the user.


    Here is the next part that will run if the first part of the loop is false:

    } else {
    echo "Wrote the following to the file:
    $text";
    }

    This else statement will ONLY run if the first part ("if could not write") is false. If this does run then that means that the script COULD write to the file! Along with letting the user know that everything is OK, we print out the value of what we put in the file ($text).


    ##################################################
    ## Checking Files
    ##################################################


    Now lets practice with some of the other functions made for files:

    is_file() - returns True/False indicating whether the specified file is a regular file
    is_executable() - returns True/False indicating whether the specified file is executable
    is_readable()- returns True/False indicating whether the specified file is readable
    is_writable()- returns True/False indicating whether the specified file is writable
    filesize() - gets size of file
    filemtime() - gets last modification time of file
    filetype() - gets file type

    (Note: you can find ALL of the functions for files at php.net)

    Lets put each one to use in a new script; type this into you editor:



    $filename = "writetest.txt";

    if (is_file($filename)) { echo "$filename is a File!
    "; }

    if (is_executable($filename)) { echo "$filename is executable!
    "; }

    if (is_readable($filename)) { echo "$filename is readable!
    "; }

    if (is_writable($filename)) { echo "$filename is writable!
    "; }

    echo " $filename is ". filesize($filename). " bytes
    ";

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename)). "
    ";

    echo "$filename is a ". filetype($filename). " file
    ";

    ?>


    Notice that every function except for is_executable was true. That is because ".txt" files are just plain text files - they are not programs.


    ###############################################
    ## Extra Information about the echo statements
    ###############################################


    Another thing that might throw you off are the periods ( . ) in some of the echo statements. Such as:

    echo " $filename is ". filesize($filename). " bytes
    ";


    These periods are a way to add different kinds of things to an echo. As you know a normal echo looks like this:

    echo "Hello World";


    You can also echo functions like this:

    echo filetype($filename);


    However, when you want to echo the results of a function within a sentence you can't do this:

    echo "Hello World, filetype($filename)";


    All you would see is "Hello World, filetype(writetest.txt)" if you ran it. And if you tried to end the text ( put a closing ")and then put in the function you would get a parse error:


    echo "Hello World" filetype($filename);
    // gives you a parse error!!!


    This is where ( . ) enters in, they tell the computer that there is more coming in the echo command:


    echo "$filename is ". filesize($filename). " bytes
    ";


    In English this code would read:
    print {{Start of Text}} (the value of "$filename") is {{End of Text}} plus ( . ) (print the size of "$filename") plus ( . ) {{Start of Text}} bytes
     {{End of Text}};


    Phew!!!! I am tired after all of this, Later! 8)