Larger Text Normal Text Smaller Text

IT 280 Web Development II, Spring 2008

 

Using files with PHP

Ways of using a file

Starting work with a file: the fopen() function

Example

      $myHandle = fopen($filename, 'w'); // opens in write mode

      $myHandle = fopen($filename, 'a'); // opens in append mode

A limitation

Creating new files

Getting text into a file: the fwrite() function

Example

    fwrite($myHandle, "this is some text to be written into the file");

Finishing up: the fclose() function

    fclose($myHandle);

Example 1

<?php
    //file firstwrite.php
    $myHandle = fopen('testfile.txt', 'w');   //Open in write mode
    fwrite($myHandle, "Line of text to be written into the file.\n");
    fwrite($myHandle, "A second line of text.\n");      
    fclose($myHandle);
?>
<body>
    <h1>Writing done.</h1>
</body>

Here is the first example.

Example 2

<?php
    //file secondwrite.php
    $myHandle = fopen('testfile2.txt', 'a');   //Open in write mode
    fwrite($myHandle, "Another line of text to be written into the file.\n");
    fwrite($myHandle, "yet another line of text.\n");      
    fclose($myHandle);
?>
<body>
    <h1>Appending done.</h1>
</body>

Here is the second example.

Safety first - the strip_tags() function

Example3

For example, the output of

    $clean = strip_tags("<p>Hello</p><?php echo 'whatever' ?>");
    echo $clean;

is just

    Hello

Here is the third example.

Important Security Precaution

Writing form data to a file