PHP
  Home arrow PHP arrow Page 3 - Reading, Writing and Creating Files in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Reading, Writing and Creating Files in PHP
By: Jacques Noah
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 34
    2006-08-23


    Table of Contents:
  • Reading, Writing and Creating Files in PHP
  • File Permissions in a Unix Environment
  • Writing to Files
  • Reading from Files

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Reading, Writing and Creating Files in PHP - Writing to Files
    ( Page 3 of 4 )

    Writing to files is a three step process in PHP. First you open the file; then you write data to it; and then you close it. PHP has built-in functions that make this easy. For example, if I want to write "My name is John Doe" to a file, I'd do it like this:

    $file_pointer = fopen('thefilename','themode');

    fwrite($file_pointer,'My name is John Doe');

    fclose($file_pointer);

    In PHP you do not work with a file directly, but through a file pointer. The file is assigned to the file pointer right at the start of the code and is then used throughout the script to read or write to the file, until the fclose() function is called.

    The most important thing about opening a file is what mode you want to use. Depending on what you want to do with the file, the mode dictates how to open it.

    Below is a table containing all the modes with their respective meanings:

    Mode

    Meaning

    r

    Reading only, begins reading a the start of the file

    r+

    Reading or writing, begins reading a the start of the file

    w

    Writing only. Creates the file if it does not exist, and overwrite any existing contents

    w+

    Reading or writing Creates the file if it does not exist, and overwrite any existing contents(when writing)

    a

    Writing only. Creates the file if it does not exist, and append the new data to the end of the file.

    a+

    Reading or writing Creates the file if it does not exist, and overwrite any existing contents(when writing)

    x

    Writing only. Creates the file if it does not exist, but do nothing, issue a warning, if the file does exist.

    x+

    Reading or Writing. Creates the file if it does not exist, but do nothing, issue a warning, if the file does exist.

    The fwrite() function writes data (as seen in the above piece of code) to the file, in accordance with the selected mode. If you want each piece of data to be written on a new line, then an appropriate new line characters should be added at the end of the line. The line break characters depend on the operating system that you are using:

    n on Unix and  MAC OS X

    rn on Windows

    The last line in our example of writing to a file closes the file by referring to the file pointer variable while calling the fclose() function.

    As an example, let's create a text file  and write names to it. Later on we will retrieve and display the names.

    First, create a text file and call it names.txt. Do not type anything in it. You can do this in any text editor. Then create a PHP document and save it as writename.php. This script will display and handle an HTML form.

    writename.php
    <?
    //check if the form has been submitted
    if(isset($_POST['submit'])){
    //try to open the file
    if($fp=fopen('names.txt','ab')){
    //write to the file
    fwrite($fp,$_POST['thename']. "rn");
    fclose($fp);
    //inform user that the writing was a success
    echo "The name ".$_POST['thename']. " has been stored";
    }else{
    echo "There was an error, could not store the name.";
    }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <title>Untitled Document</title>
    </head>
    <body>
    <form action="writename.php" method="post">
    <table width="100%" border="0" cellspacing="1">
      <tr>
        <td colspan="2">Please enter a name: </td>
        </tr>
      <tr>
        <td width="7%"><strong>Name:</strong></td>
        <td width="93%"><input name="thename" type="text" id="thename" size="40" /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="submit" value="submit" /></td>
      </tr>
    </table>
    </form>
    </body>
    </html>

    See this script in action:

    Filling out the form..

    Name added to the names.txt file.

    If your file is on a server, chances are that more than one person at a time will want to use the file at the same time. In that case, you will have a problem. Luckily for you, PHP has functions that give you the ability to lock a file while you are busy using it.

    The LOCK_EX and LOCK_UN functions will enable you to lock a file temporarily while it is being used. A revised version of our previous script would look something like this:

    <?
    //check if the form has been submitted
    if(isset($_POST['submit'])){
    //try to open the file
    if($fp=fopen('names.txt','ab')){
    flock($fp, LOCK_EX);
    //write to the file
    fwrite($fp,$_POST['thename']. "rn");
    flock($fp,LOCK_UN);
    fclose($fp);
    //inform user that the writing was a success
    echo "The name ".$_POST['thename']. " has been stored";
    }else{
    echo "There was an error, could not store the name.";
    }
    ?>



     
     
    >>> More PHP Articles          >>> More By Jacques Noah
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek