PHP and Shell Script for File Management

PHP and Shell Script for File Management

Learn how to manage files in PHP using shell scripts. Automate copying, moving, renaming, and deleting files securely with PHP and Bash commands.

Introduction

Managing files on a server is a fundamental task in web applications, automation scripts, and system administration. PHP can execute shell scripts to handle copying, moving, renaming, and deleting files efficiently.

With PHP and Bash, you can:

  • Copy and move files dynamically using PHP scripts
  • Delete and rename files securely
  • Manage large file operations using shell commands
  • Automate file transfers and cleanup tasks

This guide covers:

  • Running Bash commands from PHP for file management
  • Copying, moving, and deleting files securely
  • Handling file permissions and ownership issues
  • Automating file cleanup using cron jobs

1. Copying Files Using PHP and Shell Scripts

Using shell_exec() to Copy a File

$file = '/var/www/html/sample.txt';
$destination = '/var/www/html/backup/sample_backup.txt';

shell_exec("cp $file $destination");
echo "File copied successfully.";

Using exec() for Structured Output

$output = [];
$returnVar = 0;
exec("cp $file $destination", $output, $returnVar);

if ($returnVar === 0) {
    echo "File copied successfully.";
} else {
    echo "Error copying file.";
}

Using a Bash Script to Copy Multiple Files

PHP Code to Trigger the Bash Script

shell_exec("bash /scripts/copy_files.sh /var/www/html /var/www/backup");
echo "Copy process started.";

copy_files.sh (Bash Script to Copy Files)

#!/bin/bash
SOURCE=$1
DESTINATION=$2

cp -r $SOURCE/* $DESTINATION/
echo "Files copied from $SOURCE to $DESTINATION"

2. Moving and Renaming Files with PHP and Bash

Using PHP to Move a File

$file = '/var/www/html/sample.txt';
$newLocation = '/var/www/html/archive/sample.txt';

shell_exec("mv $file $newLocation");
echo "File moved successfully.";

Using a Bash Script to Move Files

PHP Code to Execute Bash Script

shell_exec("bash /scripts/move_files.sh /var/www/html/temp /var/www/html/archive");
echo "Files moved.";

move_files.sh (Bash Script to Move Files)

#!/bin/bash
SOURCE=$1
DESTINATION=$2

mv $SOURCE/* $DESTINATION/
echo "Files moved from $SOURCE to $DESTINATION"

Renaming a File Using PHP and Shell Script

$file = '/var/www/html/sample.txt';
$newName = '/var/www/html/sample_renamed.txt';

shell_exec("mv $file $newName");
echo "File renamed successfully.";

3. Deleting Files and Directories Securely in PHP

Deleting a File Using PHP and shell_exec()

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

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

Deleting a Directory and Its Contents

$directory = '/var/www/html/old_logs';

shell_exec("rm -rf $directory");
echo "Directory deleted.";

Using a Bash Script to Delete Old Files

PHP Code to Run the Bash Script

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

delete_old_files.sh (Bash Script to Remove Files Older Than X Days)

#!/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?

  • Removes old log files or temporary data
  • Automates server cleanup

4. Checking File Existence and Permissions in PHP

Check if a File Exists Before Performing Actions

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

if (file_exists($file)) {
    echo "File exists.";
} else {
    echo "File does not exist.";
}

Checking File Permissions Before Execution

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

if (is_writable($file)) {
    echo "File is writable.";
} else {
    echo "File is not writable.";
}

Modifying File Permissions Using PHP and Bash

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

shell_exec("chmod 644 $file");
echo "File permissions updated.";

5. Automating File Management with Cron Jobs

Scheduling a Script to Delete Old Files Automatically

To delete log files older than 7 days, create a cron job:

crontab -e

Add the following line:

0 3 * * * bash /scripts/delete_old_files.sh /var/logs 7

This executes the cleanup script every day at 3 AM.

6. Securely Running Shell Commands in PHP

Escaping User Input to Prevent Command Injection

Unsafe Code (DO NOT USE)

$filename = $_GET['file'];
shell_exec("rm $filename"); // Dangerous

Safe Code (Using escapeshellarg())

$filename = escapeshellarg($_GET['file']);
shell_exec("rm $filename");

Restricting PHP Script Execution with sudoers

To allow PHP to run privileged shell commands, add a rule in sudoers:

sudo visudo

Add the following:

www-data ALL=(ALL) NOPASSWD: /path/to/script.sh

Then, execute in PHP:

$output = shell_exec('sudo bash /path/to/script.sh');
echo "<pre>$output</pre>";

Best Practices for File Management Using PHP and Shell Scripts

  • Use Bash scripts for bulk operations
  • Escape user inputs to prevent security risks
  • Set proper permissions when handling sensitive files
  • Use cron jobs for scheduled file management
  • Test scripts in a development environment before deploying

Conclusion

PHP and shell scripts provide efficient file management for copying, moving, renaming, and deleting files on a server.

This guide covered:

  • Executing shell commands for file operations
  • Using Bash scripts to manage files dynamically
  • Automating file cleanup with scheduled tasks
  • Implementing security measures when executing shell commands

By integrating PHP with shell scripting, file management tasks can be automated and optimized efficiently.

Leave a Reply