Web Development

  Homes arrow Web Development arrow index
 Webmaster Tools
 
Base64 Encoding 
Browser Settings 
CSS Coder 
CSS Navigation Menu 
Datetime Converter 
DHTML Tooltip 
Dig Utility 
DNS Utility 
Dropdown Menu 
Fetch Content 
Fetch Header 
Floating Layer 
htaccess Generator 
HTML to PHP 
HTML Encoder 
HTML Entities 
IP Convert 
Meta Tags 
Password Encryption
 
Password Strength
 
Pattern Extractor 
Ping Utility 
Pop-Up Window 
Regex Extractor 
Regex Match 
Scrollbar Color 
Source Viewer 
Syntax Highlighting 
URL Encoding 
Web Safe Colors 
Forums Sitemap 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
WEB DEVELOPMENT

index
By: Developer Shed
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0
    2003-08-09

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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
     
     

    SEARCH DEV MECHANIC

    TOOLS YOU CAN USE

    advertisement

    WorkingWith Text Files in PHP

    By:Mitchell Harper

    Introduction

    We've come a long way since"back in the day" when itwas the "in-thing" to workwith flat-files to storeapplication data. Back then(let's say early 1990's)it was popular to save recordsin CSV formatted plain textfiles, separated by newlines.

    In 1992 I was 10 and washappily plugging away inMicrosoft QBasic, tryingto build my first ASCIIbased game by saving highscores and level data intoa plain-text file. It worked,but I wish MySQL was aroundback then!

    Today in late 2002, thingsare a lot different.

    Flat files are out and databasesare in. I have worked withSQL Server, Access and Oracle,but talking as a softwaredeveloper, I would haveto say that MySQL is themother of all databases.It's small. Fast. Sleek.Cross-platform. Easy tolearn and gets the job done.

    I love databases, but Ialso think that every developershould at least have somebasic knowledge of how toread and write files. Youmay be thinking "why wouldI need to use flat files.If I use files they're writtenin XML and I just use aparser to get what I want".Well, here are a coupleof reasons why you mightneed to work with files:

    • Tomove binary data (suchas image files) into adatabase as BLOBs (BinaryLarge Objects)
    • Toimport data (such as emailaddresses) that has beenexported from a legacydatabase or application.
    • Toexport data out of a databaseinto a text file so thatit can be processed offline

    Thereare hundreds more reasons,many of which I'm sure you'vealready thought about. Anyway,today I want to run youthrough some basic fileoperations with PHP. Filefunctions in PHP are verysimilar to those found inthe C++ fstream library,so if you've come from aC++ background and haven'tdabbled with files in PHPjust yet, then you're infor an easy ride.

    Opening and Reading Files

    More often that not, youwill be opening and readingfiles as opposed to writingthem. There are 3 main functionsthat we can use to openand read files in PHP:

    fopen
    fopen stands for "file open",and is used to create apointer to the file whichwe want to open for read/writeaccess. It accepts 2 requiredand 2 optional parameters.Its signature is shown below:

    int fopen ( stringfilename, string mode [,int use_include_path [,resource zcontext]])

    For example, let's say thatwe wanted to open a filecalled test.txt. We woulduse fopen like this:

    <?php

    $fp = fopen("test.txt","r");

    ...
    ?>

    The $fp variable would nowcontain a pointer (or reference)to the test.txt file. Thesecond parameter, "r", tellsPHP that we want to openthe file in read mode only–- we don't actually wantto write to the file. One-wayfile operations are quickerthan 2 way operations (suchas read+write access) becausethe location of the filepointer is uni-directional,i.e. it only has to traveldown the file, and not jumpfrom position to position.

    There are 6 different filemodes that we can use whenworking with files in PHP.They are shown below (courtesyof php.net):

    • 'r'- Open for reading only;place the file pointerat the beginning of thefile.
    • 'r+'- Open for reading andwriting; place the filepointer at the beginningof the file.
    • 'w'- Open for writing only;place the file pointerat the beginning of thefile and truncate thefile to zero length. Ifthe file does not exist,attempt to create it.
    • 'w+'- Open for reading andwriting; place the filepointer at the beginningof the file and truncatethe file to zero length.If the file does not exist,attempt to create it.
    • 'a'- Open for writing only;place the file pointerat the end of the file.If the file does not exist,attempt to create it.
    • 'a+'- Open for reading andwriting; place the filepointer at the end ofthe file. If the filedoes not exist, attemptto create it.
    Asyou can see, PHP is very flexiblewhen it comes to files. Wecan read a file, read andwrite to a file, append tothe end of a file, move thefile pointer to the bottomof the file automaticallyand more!

    Now that we're familiar withthe fopen function, let'slook at the feof and freadfunctions.

    feof
    Yes, it sounds like some sortof greek god name, but it'sactually the function thatwe can use in PHP to determinewhether or not we have reachedthe end of a file when we'rereading it in. All file functionsare prefixed with the character"f" in PHP, and EOF is anacronym for End-Of-File.

    Feof is a simple function,and accepts just 1 parameter,as shown below:

    intfeof ( int fp)

    The parameter, fp, is a referenceto a file pointer that containsthe details of the file we'reworking with. Feof returnstrue if we're at the end ofa file, and false if we'renot.

    Before we can see the feoffunction in action, we needto learn a bit about the freadfunction, which we will lookat next.

    fread
    I really do love the flexibilityof PHP. You can do thingsthe long way (if you've comefrom a C++ background forexample), or you can do thingsthe short way. For example,in PHP there are 2 differentfunctions that you can useto read in a file. They arecalled fgets and fread. Takea look at some code for eachin the examples below, andtell me which one you’d ratheruse:

    // fgets example

    <?php

    $fp = fopen("test.txt", "r");
    $data = "";

    while(!feof($fp))
    {
    $data .= fgets($fp, 4096);
    }

    echo $data;

    ...
    ?>

    // fread example

    <?php

    $fp = fopen("test.txt", "r");
    $data = fread($fp, filesize($fp));

    echo $data;

    ...
    ?>

    Fairly easy choice, right?Fgets grabs a line from thefile, whereas fread grabsa certain amount of charactersfrom the file. Let's examineour fread example in furtherdetail:

    $fp = fopen("test.txt", "r");

    We start by using the fopenfunction to open the "test.txt"file for reading only. Thefile pointer to test.txt isstored in the variable called$fp.

    $data = fread($fp, filesize($fp));

    Next, we grab the entire contentsof our test.txt file by passing2 parameters to the freadfunction:
    • $fpis the file pointer toour test.txt file
    • filesize($fp)is a PHP function whichaccepts a pointer to afile. It returns the lengthof that file in bytes

    Afterthis line has executed,$data will contain the entirecontents of our test.txtfile -- whether it be textor binary. The signatureof the fread function lookslike this:

    string fread (int fp, int length)

    As we've already discussed,we pass in a file pointer($fp in our example) andalso the number of bytesthat we want to retrievefrom the file. The filesize()function returns the lengthof our file by simply passingit the file pointer.

    [Note] If you'rereading in binary data ona Windows PC, then you needto use "rb" as the filemode instead of just "r".[End Note]

    Putting it All Together
    OK, so now you know aboutthe 4 functions that weneed to open and then read-inthe contents of a file:fopen(), foef(), fread()and filesize(). Let's createa PHP script that will readsome values in from a textfile.

    Create a text file called"person.data" and add thefollowing lines to it:

    Mitchell
    Harper
    20
    M

    Create a file called getperson.phpand add the following codeto it (make sure you saveit in the same directoryas person.data:

    <?php

    $fp = @fopen("person.data","rb") or die("Couldn't openfile");
    $data = fread($fp, filesize($fp));

    while(!feof($fp))
    {
    $data .= fgets($fp, 1024);
    }

    fclose($fp);

    $values = explode("\r\n",$data);

    echo "Name: " . $values[0]. " " . $values[1] . "<br>";
    echo "Age: " . $values[2]. "<br>";
    echo "Sex: " . $values[3];

    ?>

    The output from getperson.phplooks like this:



    In the example above, Idecided to use fgets() insteadof fread(). Notice alsothat I've called fclose()after I have read-in thecontents of the file. Fclose()simply releases the pointerto the file and frees upthe memory that all fileoperations associated withthat pointer were using.

    [Note] Instead of usingexplode to split the contentsof the file into an array,I could have just used

    echo $data;

    ... to output the contentsof the entire file. [EndNote]

    OK, are you familiar withhow to open and read thecontents of a file now?Good! Because now we'regoing to learn how to createand write to files...

    Creating and Writing Files

    Files are flexible. Theycan contain text or binarydata. They can contain anythingfrom a single characterto 100,000 lines of XML.It is this flexibility combinedwith PHP's simply file-handlingfunctions that make filessuch an easy-to-use aspectof PHP.

    On the last page we learnthow to open and read files.Creating and writing filesis very similar –- we startwith the fopen function:

    Here are all of the filemodes that relate to writingto a file:

    • 'w'- Open for writing only;place the file pointerat the beginning of thefile and truncate thefile to zero length. Ifthe file does not exist,attempt to create it.
    • 'w+'- Open for reading andwriting; place the filepointer at the beginningof the file and truncatethe file to zero length.If the file does not exist,attempt to create it.
    • 'a'- Open for writing only;place the file pointerat the end of the file.If the file does not exist,attempt to create it.
    • 'a+'- Open for reading andwriting; place the filepointer at the end ofthe file. If the filedoes not exist, attemptto create it.

    Soby simply specifying "w"as the file mode, PHP willmove the file pointer tothe beginning of the fileand truncate (cut-down)the file to zero lengthif that file already exists.If it doesn't exist, here'sthe good part -- PHP willautomatically create itfor us!

    So, how would we createa blank file using justthe fopen command? Simple.Take a look:

    <?php

    $fp = fopen("newfile.file","w") or die("Couldn't createnew file");

    ?>


    That's really all thereis to it. To actually outputa value to the file, weneed to use the fwrite function,which we will discuss now.Continued>>>

     

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Web Development Articles
    More By Developer Shed

       

    WEB DEVELOPMENT ARTICLES

    - On Page SEO for New Domains
    - Improve Your Site`s Speed
    - Safari Books Online Review
    - Creating an Estore From the Ground Up
    - Most Common SEO Mistakes Developers Make
    - Making the Most of Your Titles and Meta Desc...
    - Five Ways Using Flash Can Damage Your Site
    - A Web Designer`s Guide to Colors
    - Use Webstarts to Create a Free Site
    - More Than Just Looks. How Your Web Design C...
    - How to Design Content Pages
    - Mint Review
    - Make Your WordPress Website Look Professional
    - How to Create a Mobile Web Site
    - Meta Tags: Still Useful?

    Developer Shed Affiliates

     



    © 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap