Page 190 - Open Soource Technologies 304.indd
P. 190

Unit 11: Directories and Files



            11.3 Creating File                                                                    Notes

            File creation is a snap with PHP, but to make things easier we are going to make a directory
            that has permissions that allow the web server to write. Create a directory called test/ and make
            sure the permissions on it are set as explained above.

            Now that you have the right permissions you can go ahead and make your first file. Create a
            PHP script named file.php inside the test/ folder and include the following code:

            <?php
            $file = “./test.txt”;
            $fp = fopen (“$file”, “wb”);

            $content = “Hello, I am a File!”;
            fwrite($fp, $content);
            fclose($fp);

            echo “Wrote to ($file):<pre>”;
            readfile($file);
            echo “</pre>”;
            ?>
            So what does all that do?

            First off we have $file which just sets the name of the file you are creating with the script, in
            this case file.txt.

            Next we have $fp or “file pointer” this is used with the fopen() function to first look for a file
            (specified by $file) and if not found create it. fopen() will be described in more detail in the
            next section.
            The contents of the file will be determined in this case by the variable $content, and will be
            written to the file by the function fwrite(). You should now close your file, as you do not need
            to  write  anymore  data  to  it  via  fclose().  For  this  example,  we  will  print  out  what  has  been
            written to the file:

            readfile($file) .
            If the script has run correctly, you will see something like this:

            Wrote to (./test.txt):
            Hello, I am a File!

            More on fopen();
            Now let’s look a little more closely at what is going on here.
            fopen() is the command that opens the file for reading or writing. It accepts a filename and one
            of six arguments: r, r+, w, w+, a, a+ as well as b for binary safe writing of files (Windows needs
            this for non-text files, for Unix it doesn’t matter. The safest way is thus to always use the “b”
            when working with binary, non-text files.)

            In our case we used wb to open a binary file for writing only. This will truncate the file length
            to zero so that the file is blank and then place the content at the beginning of the file. If the file
            does not exist, it will attempt to create it.



                                             LOVELY PROFESSIONAL UNIVERSITY                                   185
   185   186   187   188   189   190   191   192   193   194   195