What are the best practices for handling file operations in PHP, especially when involving external scripts like batch files?

When handling file operations in PHP, especially when involving external scripts like batch files, it is important to properly sanitize input to prevent security vulnerabilities. Additionally, using absolute file paths and checking for file existence before performing operations can help avoid errors. Lastly, utilizing PHP's built-in functions like exec() or shell_exec() to execute external scripts can provide more control and security.

// Example of handling file operations with external script in PHP
$batchFile = 'C:/path/to/external_script.bat';
$inputFile = 'C:/path/to/input_file.txt';
$outputFile = 'C:/path/to/output_file.txt';

// Sanitize input
$batchFile = escapeshellarg($batchFile);
$inputFile = escapeshellarg($inputFile);
$outputFile = escapeshellarg($outputFile);

// Check if files exist
if (file_exists($batchFile) && file_exists($inputFile)) {
    // Execute external script
    $command = "$batchFile $inputFile $outputFile";
    exec($command, $output, $returnCode);

    if ($returnCode === 0) {
        echo "External script executed successfully.";
    } else {
        echo "Error executing external script.";
    }
} else {
    echo "Files do not exist.";
}