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

Unit 11: Directories and Files



            <?                                                                                    Notes
            $body_content=”This is my content”; // Store some text to enter inside the file
            $file_name=”test_file.txt”; // file name
            $fp = fopen ($file_name, “w”); // Open the file in write mode, if file does not
            fwrite ($fp,$body_content); // entering data to the file
            fclose ($fp);                         // closing the file pointer
            chmod($file_name,0777);   // changing the file permission.

            ?>
            11.6.3 File Write: Overwriting

            Now that testFile.txt contains some data we can demonstrate what happens when you open an
            existing file for writing. All the data contained in the file is wiped clean and you start with an
            empty file. In this example we open our existing filetestFile.txt and write some new data into it.
            PHP Code

                          $myFile = “testFile.txt”;

                          $fh = fopen($myFile, ‘w’) or die(“can’t open file”);
                          $stringData = “Floppy Jalopy\n”;

                          fwrite($fh, $stringData);
                          $stringData = “Pointy Pinto\n”;

                          fwrite($fh, $stringData);
                          fclose($fh);


            If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as
            we expected, and only the data we just wrote is present.

            Contents of the TestFile.txt File

                          Floppy Jalopy

                          Pointy Pinto


            11.7 Appending Files


            So far we have learned how to open, close, read, and write to a file. However, the ways in which
            we have written to a file so far have caused the data that was stored in the file to be deleted.
            If you want to append to a file, that is, add on to the existing data, then you need to open the
            file in append mode.

            Again, we attempt to open the file. This time we’re passing mode ‘a’. This is what we use to
            append the text to the end of the file. If you wish to add data to the end of the file and keep
            from overwriting the previous data, this is the mode you want to use.

            So again we set a $line variable and write it to the file. This time, the line is added to the end
            of the file. You can open the file and take a look, and you’ll see that the text is written on the
            next line.


                                             LOVELY PROFESSIONAL UNIVERSITY                                   189
   189   190   191   192   193   194   195   196   197   198   199