How to Read and Write Files Using PHP and Bash Scripts

How to Read and Write Files Using PHP and Bash Scripts

Learn how to read and write files using PHP and Bash scripts. Handle text files, modify data, and automate file processing securely with PHP and shell scripting.

Introduction

Reading and writing files in PHP is essential for data storage, configuration management, log handling, and automation. While PHP provides built-in file-handling functions, integrating Bash scripts allows for better performance and system-level automation.

With PHP and Bash, you can:

  • Read text files and log data dynamically
  • Write structured data into files
  • Automate file processing tasks using shell scripts
  • Handle large files efficiently without performance issues

This guide covers:

  • Reading and writing files in PHP
  • Using Bash scripts for file manipulation
  • Automating file updates and logs
  • Securing file operations to prevent unauthorized access

1. Reading Files in PHP

Reading a File Using file_get_contents()

$file = '/var/www/html/data.txt';

if (file_exists($file)) {
    $content = file_get_contents($file);
    echo nl2br($content);
} else {
    echo "File not found.";
}

Reading a File Line by Line Using fopen()

$file = '/var/www/html/data.txt';

if ($handle = fopen($file, "r")) {
    while (($line = fgets($handle)) !== false) {
        echo nl2br($line);
    }
    fclose($handle);
} else {
    echo "Unable to open file.";
}

Why Use This?

  • Efficient for reading large files
  • Supports line-by-line processing

2. Writing to a File in PHP

Using file_put_contents() to Write Data

$file = '/var/www/html/data.txt';
$data = "This is a new line of text.\n";

file_put_contents($file, $data, FILE_APPEND);
echo "Data written successfully.";

Using fopen() and fwrite() for More Control

$file = '/var/www/html/data.txt';
$data = "Appending a new line.\n";

if ($handle = fopen($file, "a")) {
    fwrite($handle, $data);
    fclose($handle);
    echo "Data appended successfully.";
} else {
    echo "Unable to write to file.";
}

Why Use This?

  • Allows appending or overwriting data
  • Provides better control over file operations

3. Reading Files Using a Bash Script in PHP

To read a file using a Bash script, execute the script from PHP.

PHP Code to Run the Bash Script

$file = '/var/www/html/data.txt';
$output = shell_exec("bash /scripts/read_file.sh $file");
echo "<pre>$output</pre>";

Bash Script (read_file.sh)

#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
    cat "$FILE"
else
    echo "File not found."
fi

Why Use This?

  • Handles large files more efficiently than PHP
  • Processes system-level files securely

4. Writing Data to a File Using Bash from PHP

PHP Code to Execute a Bash Script for Writing Data

$file = '/var/www/html/data.txt';
$data = "New entry added at " . date('Y-m-d H:i:s');

shell_exec("bash /scripts/write_file.sh '$file' '$data'");
echo "Data written using Bash.";

Bash Script (write_file.sh)

#!/bin/bash
FILE=$1
DATA=$2

echo "$DATA" >> "$FILE"
echo "Data written to $FILE"

Why Use This?

  • Ensures safe file writing on Linux systems
  • Useful for logging and automated data updates

5. Reading Large Files in PHP Efficiently

For large files, use memory-efficient methods like SplFileObject:

$file = new SplFileObject('/var/www/html/large_data.txt');

while (!$file->eof()) {
    echo $file->fgets();
}

Why Use This?

  • Prevents memory overload
  • Reads files line by line efficiently

6. Automating File Processing Using PHP and Bash

Example: Automatically Updating a Log File

PHP Code to Run the Log Update Script

shell_exec("bash /scripts/update_log.sh");
echo "Log updated.";

Bash Script (update_log.sh)

#!/bin/bash
LOG_FILE="/var/www/html/system.log"

echo "$(date): Log entry added." >> $LOG_FILE
echo "Log file updated."

Why Automate File Processing?

  • Ensures real-time updates to logs and reports
  • Minimizes manual intervention

7. Deleting Files Securely in PHP

Deleting a File Using unlink()

$file = '/var/www/html/old_data.txt';

if (file_exists($file)) {
    unlink($file);
    echo "File deleted successfully.";
} else {
    echo "File not found.";
}

Using Bash to Delete Multiple Files

PHP Code to Execute a Bash Deletion Script

shell_exec("bash /scripts/delete_old_files.sh /var/logs 30");
echo "Old files cleanup initiated.";

Bash Script (delete_old_files.sh)

#!/bin/bash
DIRECTORY=$1
DAYS=$2

find $DIRECTORY -type f -mtime +$DAYS -delete
echo "Deleted files older than $DAYS days from $DIRECTORY"

Why Use This?

  • Automates server cleanup tasks
  • Improves performance by removing old data

8. Managing File Permissions in PHP

Changing File Permissions Using chmod()

$file = '/var/www/html/secure.txt';

chmod($file, 0644);
echo "File permissions updated.";

Using Bash to Change Permissions

shell_exec("chmod 644 /var/www/html/secure.txt");
echo "Permissions updated using Bash.";

Why Use This?

  • Prevents unauthorized file access
  • Ensures proper security on shared hosting environments

9. Scheduling File Updates with Cron Jobs

To update a file periodically, schedule a cron job:

crontab -e

Add the following line to run the log update script every 6 hours:

0 */6 * * * bash /scripts/update_log.sh

10. Best Practices for File Handling with PHP and Bash

  • Use Bash scripts for handling large files
  • Escape file paths in PHP (escapeshellarg()) to prevent security risks
  • Ensure proper permissions to avoid unauthorized modifications
  • Schedule periodic file updates using cron jobs
  • Use memory-efficient methods (SplFileObject) for large file reading

Conclusion

Reading and writing files using PHP and Bash provides efficient automation for file management, log processing, and system updates.

This guide covered:

  • Reading and writing files in PHP using built-in functions
  • Executing Bash scripts for file handling tasks
  • Automating file operations like logging and cleanup
  • Implementing security best practices for file access

By integrating PHP with Bash, file operations can be optimized, automated, and secured effectively.

Leave a Reply