PHP Introduction | Using Text Files | Saving Files with fputs

Now let us save a file. For this, we use a function called fputs. It is called in the following form.

fputs(file pointer, data);

This alone can save data to a file. When writing to a file, the point you must be careful about is the access mode. There are two write access modes, so do not confuse them.

When you specify 'w', it is “overwrite mode.” If the file already exists, it is deleted, a new file is created, and the data written with fputs is saved there.

When you specify 'a', it is “append mode.” If the file already exists, the content written with fputs is added to the end of that file. In other words, data is added one after another with fputs.

Use these two modes properly according to the purpose. Now let us look at a simple example.

<?php
    // Add data
    if ($_POST != null){
        $f = @fopen("data.txt",'a') or exit("The file cannot be read.");
        if ($f != null){
            $s = $_POST['text1'];
            fputs($f,$s . "\n");
            fclose($f);
        }
    }
    // Read the file
    $f2 = @fopen("data.txt",'r') or exit("The file cannot be read.");
    $result = '';
    $i = 1;
    while(!feof($f2)){
        $s2 = htmlspecialchars(fgets($f2));
        if ($s2 != ""){
            $result = $i++ . ": " .$s2 . "<br>" . $result;
        }
    }
    fclose($f2);
?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Hello PHP!</h1>
        <form method="post" action="./index.php">
            <input type="text" name="text1">
            <input type="submit">
        </form>
        <hr>
        <p><?php echo $result; ?></p>
    </body>
</html>

This is an application that can write simple memos. When you enter text in the input field and submit it, the content is added to a file. Below the input form, the saved memos are displayed from newest to oldest with numbers.

Here, both “saving a file” and “reading a file” are used. Look closely at how each part works. Once you can access files, you will gradually be able to build more practical things like this.

File permission errors in Linux or Mac OS environments
If data is not appended to the file on Linux or Mac OS, check whether the file has write permission. If it does not, you can grant write permission with the following command.

$ chmod 666 data.txt 

For more details about file permissions, look up Linux commands.