Broad Network


PHP File Handling Basics and Basic Security

Basics of PHP with Security Considerations – Part 15

Foreword: In this part of the series, you learn the basics on accessing files in PHP.

By: Chrysanthus Date Published: 18 Jan 2018

Introduction

This is part 15 of my series, Basics of PHP with Security Considerations. In this part of the series, you learn the basics on accessing files in PHP. I assume that you have read the previous parts of the series before reaching here, as this is the continuation. I will consider only text files and those, which are in the working directory. This means that your test code should remain in the working directory.

Resource
In order for you to use a file in the hard disk or some other drive, you have to do what is called opening the file. For this, the content of the file is copied into memory. This area in memory that has the content of the file is called a stream (precisely a buffer). Whatever you want to do to the file (modifying the file, adding text to the end of the file, or just reading the file) you do to the stream. After that you have to $ pi4ms called cLkóilg the`by]'&6v"|;&n"spháO a néLabi# #Uo#m$ ôx% cNntent ïf 6h% sUråAmâys #opHed tg Tle(fIhu )b `je"$es{. if$nuaesqazp.Eî9 /NdIfésatioo ëf stream cmn|Dnô0or addinG ïv teptp 4`e end of the streqm`aq zdglàcðed in the`fiLe¤in the$lyQOdábWup8g sqmnw$A"fsm-)oaq!not eXiód iJ"ärd dirk© ÚIaópée@ns you hevu"to cr'ate it~ fz Dlió p7rposE, iou still he~up¯(u1e tme´mpenigg€tbmce3s qem!â%l-V)*€Q¦!dpe!o Ons`òHL¡~e7Fy9=.%d %0isUing) o`a.}f#fåma q RrEiôU`. Yo7 sejd0cnFkrmation tw ôhebstreai.0Uhen yoõ c.Ocåpvh%fHle, effeãti6eDX ó|,sí.e ]ie!sðråamn$txe`kn_t5f4)oò 4`e sprucm is so0Auìp\ë t*m Dmrk® Snosin' af)\eÃuMhîC$puE\-Ös an0ehl8Vo phu"associati?~` mtwm%^$`m)cT2lqë ånt`the cïsr#cpmfdin' FHìu i."tA$ dHsk, afôerbthe cgntand -f th ódream has0j5stfEaN ãpied to thedmte,¤shyáh ?i'`t raeÍgèd0n/< h@ve ep)Sxdd, in ôhdbàIsë.<"z>Fnte: v`mgoneeª| /fbUhe strecm(hs ôhebfile"goVan\"Ãsqied fr-m dirk¨ if@tèT fhlá exióte& il |me1físk before ytdOa±xGpå~ed. Whkmm¥yoq ;pMetkti.g @ file, the content may also be saved.

In order to open, edit and close a file, you need what is known as a resourse. A resourse is a special kind of reference holding variable. There are different kinds of resourses - see later.

The simplified syntax to open a file is,

    resource fopen($filename, $mode)

The function returns a file pointer resource on success, or FALSE on error. The first argument in the parentheses is the file name in quotes. I will explain the role of the mode (second) argument as we go along.

The simplified syntax to close a file is,

    bool fclose($handle)

where $handle is the returned resource above. Any file opened has to be closed, after editing.

The function returns TRUE on success or FALSE on failure.

Text files are created in lines of text. The following simplified syntax reads a line of text from a file:

    string fgets($handle)

This function returns the line of text including the newline character (\n). It will return FALSE if there is no more line to read. It will still return FALSE if an error occurs. Note that the content of a line may be NULL or 0. So to test for FALSE, use === or !== .

The following simplified syntax writes a line of text to a file:

    int fwrite ($handle, $string)

where $handle is the same resource from fopen(), and $string in double quotes, ends with a newline character (\n). The function returns the number of bytes written, or FALSE on error. Note that the integer returned may be zero. So to test for FALSE, use === or !== .

Modes
The following are the possible values for the $mode variable above:

'r': Open for reading only; place the file pointer at the beginning of the file.  
'r+': Open for reading and writing; place the file pointer at the beginning of the file.  
'w': 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.  
'w+': Open for reading and writing; 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.  
'a': Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  
'a+': Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  
'x': Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.  
'x+': Create and open for reading and writing; otherwise it has the same behavior as 'x'.  
'c': Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).  
'c+': Open the file for reading and writing; otherwise it has the same behavior as 'c'.  

Writing a File
The following code creates a new file and writes lines of text to it.

<?php

    if (!$handle = fopen('temp1.txt', 'w'))
        {
            echo "Cannot open file 'temp1.txt'";
        }
    else
        {
            if (fwrite($handle, "The first line.\r\n") === false)
                {
                    echo "Cannot write 'The first line.\n' to temp.txt";
                }
            if (fwrite($handle, "The second line.\r\n") === false)
                {
                    echo "Cannot write 'The second line.\n' to temp.txt";
                }
            if (fwrite($handle, "The third line.\r\n") === false)
                {
                    echo "Cannot write 'The third line.\n' to temp.txt";
                }

            echo 'Data written';

            fclose($handle);

        }

?>

The file content is:

The first line.
The second line.
The third line.

The expression,

    $handle = fopen('temp1.txt', 'w')

results in $handle, which is either the resource or false. It it is false, then !$handle is true. Note the mode that has been used in the above code.

Reading a File
The following code opens and reads the lines of text from a file:

<?php

    if (!$handle = fopen('temp1.txt', 'r'))
        {
            echo "Cannot open file 'temp1.txt'";
        }
    else
        {
            while (($buffer = fgets($handle)) !== false)
                {
                    echo $buffer, "<br>";
                }

            fclose($handle);

        }

?>

The output is:

The first line.
The second line.
The third line.

Note the mode that has been used in the above code. The expression,

    $buffer = fgets($handle)

results in $buffer, which either has the line of text or "false". It is compared to false with the Not Identical operator. The while-loop reads lines of text until the end-of-file. After the reading of each line, the file pointer points to the next line.

Appending to a File
"Append" means add lines to the bottom. The following code appends a fourth line to the file, temp1.txt :

<?php

    if (!$handle = fopen('temp1.txt', 'a'))
        {
            echo "Cannot open file 'temp1.txt'";
        }
    else
        {
            if (fwrite($handle, "The fourth line.\r\n") === false)
                {
                    echo "Cannot write 'The first line.\n' to temp.txt";
                }

            echo 'Data written';

            fclose($handle);

        }

?>

Note the mode that has been used in the above code. The file content becomes,

The first line.
The second line.
The third line.
The fourth line.

Editing a File
To edit a file, open the file in the 'r+' mode. Change the line, while it is read. The following code illustrates this, changing the second line:

<?php

    if (!$handle = fopen('temp1.txt', 'r+'))
        {
            echo "Cannot open file 'temp1.txt'";
        }
    else
        {
            while (($buffer = fgets($handle)) !== false)
                {
                    if ($buffer === "The second line.\r\n")
                        {
                            $stringlength = strlen($buffer);
                            fseek($handle, -$stringlength, SEEK_CUR);
                            $buffer = "The B line.\r\n";
                            fwrite($handle, $buffer);
                            echo $buffer, "<br>";
                        }
                     else
                         {
                             echo $buffer, "<br>";
                         }
                }

            fclose($handle);

        }

?>

Whenever a line is read, the file pointer is made to point to the next line. The following code segment takes back the file pointer to the beginning of the line read:

        $stringlength = strlen($buffer);
        fseek($handle, -$stringlength, SEEK_CUR);

The new file content is:

The first line.
The B line.
ne.
The third line.
The fourth line.

This means that the last characters, 'ne.\r\n' of the second line were not removed. I will explain how to solve this problem in a later series.

Shortcuts
Consider the funcrion:

    int file_put_contents($filename, $string)

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten.

The function returns the number of bytes (characters) that were written to the file, or FALSE on failure. The function may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Use === or  !== for testing the return value of this function.

The following code illustrates its use:

<?php

    $str = "The first line.\r\nThe second line.\r\nThe third line.\r\n";

    if (file_put_contents('temp1.txt', $str) !== false)
        {
            echo 'file created and written to, successfully';
        }

?>

Consider the funcrion:

    string file_get_contents($filename)

This function is identical to calling fopen(), fgets() and fclose() successively to read all file data into a string.

The function returns the read data or FALSE on failure (the returned string may be "").

The following code illustrates its use:

<?php

    $str;

    if (($str = file_get_contents('temp1.txt')) !== false)
        {
            echo $str;
        }

?>

That is it for this part of the series.

Chrys

Related Links

Basics of PHP with Security Considerations
More Related Links
Pure PHP Mailsend - sendmail
PurePHP MySQL API
Using the PurePHP MySQL API
Cousins
KaòwS:yípt/EC-A“RrHPt0S/;Vc÷,/i?<"r>( /b¬íref='lter¾//vwó.broad nõdwgso.smm/ChrysanthusForcha-1/Optimuo-XdRl­Co$aogªhtm'.Ø%Z" ckuzsE8/a>

Š ~a hrgf5&PHP-OOP-Basicc.(|m' s5yèD='float:Leæd'>sôbong>JÁco~¯ctr/~g_4/c6(k`2ÑáBL#?<òap ae='EA1'> =A÷ôýcee„md='coemEjts' style='textaìygn:center'>J ,c#:`pð type9'dgxv/mbiasa2aPt§-Š°0 function checkMeicqôchix))M  0zMŽ $ ` if!¨¬q'{vilS}Gr@oavgaldrDgGMj !9 ~wll)&&(sesh_ìStoragef/kus(); `( d 0} ! ¤ 0$%d3m if (((sEsÓyï~Stor`GÁ®¢uaEevNíHnæ--"nudl x|(Suã#!gnStopaod.rmaDarLÏçê<î<="â9)&((sessiG,óhOrag%.uSaugrD~g)f <=¤îul.)||(sessiofStkúqGa.writerLogin =? *#))+a( 0 h ,{=`(   b ! ¤ alert( OfgyHembdr÷"`&ñ 6riTar{ Cej0s-ementp ˆG`An Yku áre a member, Login. \n Otherwise, click the Become a Member link above, to register."); document.getElementById('BaM').focus(); } } function submitComment() { if (document.getElementById('comment').value == "") { alert('Comment box cannot be empty!'); return; } var myAjax; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari myAjax = new XMLHttpRequest(); } else {// code for IE5, IE6 myAjax = new ActiveXObject("Microsoft.XMLHTTP"); } myAjax.onreadystatechange=function() { if (myAjax.readyState == 4) { if (myAjax.status == 200) { //give feedback to user and clear text area alert('Comment has been sent.'); document.getElementById('comment').value = ""; } else { alert('There is a technical problem at the server. Try again, later.'); } } } //replace \r\n|\n with
var subject = document.getElementById('comment').value; var modifiedStr = subject.replace(/\r\n|\n/g, "
"); sendStrC = 'writerID='+writerID+'&articleID='+articleID+'&partNo='+partNo+'&readerID='+readerID+'¤tURL='+currentURL+'&comment=' + modifiedStr; myAjax.open("POST", "http://www.broad-network.com/submitComment.php", true); myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); myAjax.send(sendStrC); //display the comment on page document.getElementById('PC1').innerHTML = modifiedStr; } //get the comments var ajaxObj; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ajaxObj = new XMLHttpRequest(); } else {// code for IE5, IE6 ajaxObj = new ActiveXObject("Microsoft.XMLHTTP"); } ajaxObj.onreadystatechange=function() { if (ajaxObj.readyState == 4) { if (ajaxObj.status == 200) { document.getElementById('comBox').innerHTML = ajaxObj.responseText; } else { //alert('There is a technical problem at the server. Try again, later.'); } } } sendStrCs = 'articleID='+articleID+'&partNo='+partNo; ajaxObj.open("POST", "http://www.broad-network.com/getComments.php", true); ajaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxObj.send(sendStrCs);

Become the Writer's Follower
Send the Writer a Message