Thursday, November 28, 2024

Introduction to Working with Text Files in PHP, Reading and Writing

Working with text files in PHP is a fundamental yet crucial skill for any PHP developer. Files allow for the storage, reading, and management of data outside of an application's memory, which is essential for many applications, such as logging, storing configurations, or managing user data. This blog post provides a detailed introduction to the basics of working with text files in PHP, including reading, writing, and some advanced operations. Although databases are the predominant storage medium for data today, text files still hold their place in many applications. To proficiently work with text files in PHP, a solid grasp of fundamental concepts is essential. These include understanding file paths, which can be either relative or absolute, and file modes, which dictate whether you're reading, writing, or performing both actions on a file.

  • r - Read only. - Opens a file for reading only. Any attempt to write to the file will fail.
  • w - Write only. - Opens a file for writing only. If the file exists, it will be truncated (empty). If it doesn't exist, a new file will be created.
  • a - Append. - Opens a file for writing. Any data written will be placed at the end of the file. This is useful for adding new data to an existing file without overwriting the existing content.
  • r+ - Read and write. - Opens a file for both reading and writing. The file pointer will be positioned at the beginning of the file.

Programmers are pleasantly surprised by PHP's functions for reading and writing to text files

Programmers are pleasantly surprised by PHP's functions for reading and writing to text files

PHP offers several methods for reading content from text files. Some of the most commonly used methods include using the file_get_contents function which allows reading the entire file content in one go, using the fopen and fread functions which provide more control, especially when working with large files, and using the file function which loads the file as an array where each element is a line. Writing data to text files is a fundamental aspect of PHP programming. The file_put_contents function provides a straightforward way to write to a file, overwriting any existing content. For more granular control over the writing process, the fopen and fwrite functions offer greater flexibility. When appending data to an existing file, the FILE_APPEND mode should be used with file_put_contents.

It's essential to consider security when working with files, implementing measures such as file locking and input validation to prevent potential vulnerabilities. By mastering these concepts, you can effectively leverage file operations to manage data in your PHP applications. Working with text files in PHP is simple and efficient thanks to the built-in functions that the language provides. Whether you need to read data from a file, write logs, or even work with CSV format, PHP offers robust tools for these tasks. We hope our practical examples and tips will help you better understand and utilize the capabilities that PHP provides for working with text files. Let's move on to the practical part.

Efficient Management for Adding, Deleting, and Saving Items in an HTML List

Instead of just writing some PHP code to read and write text to a file, we decided to give our example a purpose. Although it's not a common practice, we'll create a ListBox that allows users to add and remove items. Thanks to PHP functions for reading and writing to text files, our ListBox will be able to save the user's input. We'll also make sure that the user can't enter duplicate items into the ListBox. Let's dive into our PHP tutorial. 

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ cd /opt/lampp

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:/opt/lampp$ sudo ./manager-linux-x64.run

When the XAMPP  manager window opens, start the Apache Web Server and open Visual Studio Code. Click on index.php, then in the code editor panel, modify the following part of the code.

<?php

    $title = 'PHP Tutorial';

    require_once 'includes/header.php';

?>

<h2 class="bg-primary text-light text-center py-3">Contents</h2>

<div class="container">

    <div>

        <h2><font color="seagreen">Lessons</font></h2>

        <ul>

        <li><a href="lessons/lesson01.php">

            Lesson 1. - The text printing and comments

        </a></li>

        <li><a href="lessons/lesson02.php">

            Lesson 2. - Variables and data types  

        </a></li>

        <li><a href="lessons/lesson03.php">

            Lesson 3. - Operators

        </a></li>

        <li><a href="lessons/lesson04.php">

            Lesson 4. - Conditional Statement if-else

        </a></li>

        <li><a href="lessons/lesson05.php">

            Lesson 5. - Conditional Statement switch-case

        </a></li>

        <li><a href="lessons/lesson06.php">

            Lesson 6. - The while Loop

        </a></li>

        <li><a href="lessons/lesson07.php">

            Lesson 7. - The do-while Loop

        </a></li>

        <li><a href="lessons/lesson08.php">

            Lesson 8. - The for Loop

        </a></li>

        <li><a href="lessons/lesson09.php">

            Lesson 9. - The foreach Loop

        </a></li>

        <li><a href="lessons/lesson10.php">

            Lesson 10. - The Arrays    

        </a></li>

        <li><a href="lessons/lesson11.php">

                Lesson 11. - 10 Key Strategies for Preventing Errors in PHP Programming

        </a></li>

        <li><a href="lessons/lesson12.php">

                Lesson 12. - Unlocking the Power of PHP Functions

        </a></li>

        <li><a href="lessons/lesson13.php">

                Lesson 13. - Read and Write Data to a File Using PHP

        </a></li>

        </ul>

    </div>

</div>

<!-- footer -->

<?php require_once 'includes/footer.php'; ?>


Go to the lessons folder and create a new PHP file and name it lesson13.php. In lesson13.php file enter the following PHP and HTML code which will create a form with a TextBox, Buttons, and a ListBox, and allow the user to add items to the ListBox.

<?php

    // Sets the page title

    $title = 'Lesson 13';

    // Includes the header title

    require_once '../includes/header.php';

?>

<h2 class="bg-primary text-light text-center py-3">

    Read and Write Data to a File Using PHP

</h2>

<div class="container">

<h4>Managing Items in a ListBox</h4>

<form method="POST" class="p-4 border rounded shadow">  

    <div class="mb-3">

    <label for="item" class="form-label">New item:</label>

    <input

    type="text"

    name="item"

    id="item"

    class="form-control"

    placeholder="Enter Item"

    >

    </div>

    <div class="mb-3">

    <label for="listbox" class="form-label">Items:</label>

    <select

    name="selected_item"

    id="listbox"

    class="form-select"

    size="10"

    <?php if (isset($_POST['remove'])) echo 'required'; ?>

    >

    <?php if (empty($items)): ?>

    <option disabled>The list is empty</option>

    <?php else: ?>

    <?php foreach ($items as $item): ?>

    <option value="<?= htmlspecialchars($item) ?>"><?= htmlspecialchars($item) ?></option>

    <?php endforeach; ?>

    <?php endif; ?>

    </select>

    </div>

    <div class="d-flex gap-2">

        <button type="submit" name="add" class="btn btn-primary w-100">Add</button>

        <button type="submit" name="remove" class="btn btn-danger w-100">Remove</button>

    </div>

</form>

</div>

<!-- footer -->

<?php require_once '../includes/footer.php'; ?>


A HTML form with ListBox that allows you to add and remove items

A HTML form with ListBox that allows you to add and remove items

To make our form functional, it's necessary to write the following PHP code so that it's displayed before the form. As you can see, even the HTML form contains PHP code that populates the ListBox with items and checks if the list has items to be removed. If there are no items, it disables the Remove button and displays a placeholder text indicating that the list is empty. But where does it get the items for the list? Take a look at the following code.

<?php

    /// File name for storing data

    $dataFile = "listbox_data.txt";

    // Function to read items from file with error handling

    function readItems($dataFile) {

        if (!file_exists($dataFile)) {

            try {

                touch($dataFile);                   

            } catch (Exception $e) {

                echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";

                return [];

 

            }

        }

        try {

            $contents = file($dataFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            return $contents;

        } catch (Exception $e) {

            echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";

            return [];

        }

    }

    // Function to write items to a file with error handling

    function writeItems($dataFile, $items) {

        try {

            file_put_contents($dataFile, implode(PHP_EOL, $items));

        } catch (Exception $e) {

            echo "<p style='color: red;'>Error: " . $e->getMessage()"</p>";

         }

    }

    // Processing requests to add or remove items

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        $items = readItems($dataFile);

        // Sort items alphabetically

        sort($items);

        if (isset($_POST['add']) && !empty(trim($_POST['item']))) {

            $newItem = trim($_POST['item']);

            if (!in_array($newItem, $items)) { // Check duplicates

                $items[] = $newItem;

            }

        }

        if (isset($_POST['remove']) && isset($_POST['selected_item'])) {

            $selectedItem = $_POST['selected_item'];

            $items = array_filter($items, fn($item) => $item !== $selectedItem);

        }

        writeItems($dataFile, $items);

        header("Location: " . $_SERVER['PHP_SELF']); // Refresh the page

        exit();

    }

    $items = readItems($dataFile);

?>


A ListBox that saves items even when you leave the web page

A ListBox that saves items even when you leave the web page

As soon as you reach page 13 of this tutorial, PHP checks if you have created a file named listbox_data.txt. If you don't have it, it will create it for you. If you do have the mentioned file, it will read all the items from it and display them in a ListBox. This code will also sort your items alphabetically in the ListBox and, most importantly, it will ensure that the user cannot enter duplicates into the ListBox. Then it will focus on removing the selected list item by clicking the Remove button. If you look in the text file listbox_data.txt, you will see that whatever items you have in the ListBox, you also have in the file. Pay attention to how little code is needed and how professionally PHP has handled this task. If you want to see how this whole process was created, watch the following video:


PHP – 13. How to Read and Write Data to a File?




 

 

No comments:

Post a Comment