Skip to content

Instantly share code, notes, and snippets.

@miztizm
Created December 5, 2025 14:08
Show Gist options
  • Select an option

  • Save miztizm/31384c0a18429bcf0b1f0eacf38b3689 to your computer and use it in GitHub Desktop.

Select an option

Save miztizm/31384c0a18429bcf0b1f0eacf38b3689 to your computer and use it in GitHub Desktop.
PHP & JavaScript File Compressor - Creates tar.gz backup of all PHP and JS files
<?php
/**
* PHP & JavaScript File Compressor
*
* Recursively finds and compresses all PHP and JavaScript files
* from the parent directory into a tar.gz archive.
*
* Features:
* - Recursive file discovery
* - Secure error reporting
* - Memory and execution time optimization
* - Comprehensive logging
* - Cross-platform compatibility
*
* @author miztizm
* @version 2.0
*/
// ============================================
// CONFIGURATION
// ============================================
// Set execution environment
ini_set('max_execution_time', '0'); // No timeout
ini_set('memory_limit', '1024M'); // 1GB memory
ini_set('display_errors', 1); // Show errors
ini_set('display_startup_errors', 1); // Show startup errors
error_reporting(E_ALL); // Report all errors
// Define constants
define('BASE_PATH', dirname(__FILE__));
define('PARENT_PATH', dirname(BASE_PATH));
define('ARCHIVE_NAME', 'php-js-' . date('Y-m-d_H-i-s') . '.tar.gz');
define('ARCHIVE_PATH', BASE_PATH . DIRECTORY_SEPARATOR . ARCHIVE_NAME);
// ============================================
// HELPER FUNCTIONS
// ============================================
/**
* Log messages to file and display
*
* @param string $message The message to log
* @param string $level The log level (INFO, WARNING, ERROR, SUCCESS)
*/
function logMessage($message, $level = 'INFO') {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[{$timestamp}] [{$level}] {$message}\n";
// Display in browser
echo htmlspecialchars($logEntry);
// Log to file
$logFile = BASE_PATH . DIRECTORY_SEPARATOR . 'compress.log';
file_put_contents($logFile, $logEntry, FILE_APPEND);
}
/**
* Check if command exists on the system
*
* @param string $command The command to check
* @return bool True if command exists
*/
function commandExists($command) {
$checkCommand = (PHP_OS_FAMILY === 'Windows')
? "where {$command}"
: "which {$command}";
$result = shell_exec($checkCommand . ' 2>/dev/null');
return !empty($result);
}
/**
* Format bytes to human-readable size
*
* @param int $bytes The number of bytes
* @return string Formatted size
*/
function formatBytes($bytes) {
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
}
// ============================================
// MAIN COMPRESSION LOGIC
// ============================================
try {
logMessage('Starting PHP & JS file compression...', 'INFO');
// Check if tar command exists
if (!commandExists('tar')) {
throw new Exception('tar command not found on system');
}
logMessage('Scanning for PHP and JS files in: ' . PARENT_PATH, 'INFO');
// Build find command with proper escaping
$findCommand = sprintf(
'find %s -type f \( -name "*.php" -o -name "*.js" \) 2>/dev/null',
escapeshellarg(PARENT_PATH)
);
// Execute find command and pipe to tar
$tarCommand = sprintf(
'%s | tar -czf %s -T - 2>&1',
$findCommand,
escapeshellarg(ARCHIVE_PATH)
);
logMessage('Executing compression command...', 'INFO');
$output = [];
$returnCode = 0;
exec($tarCommand, $output, $returnCode);
// Check if compression was successful
if ($returnCode !== 0 && !file_exists(ARCHIVE_PATH)) {
throw new Exception('Compression failed with return code: ' . $returnCode);
}
// Check archive was created
if (!file_exists(ARCHIVE_PATH)) {
throw new Exception('Archive file was not created');
}
// Get archive statistics
$archiveSize = filesize(ARCHIVE_PATH);
$archiveSizeFormatted = formatBytes($archiveSize);
logMessage('Archive created successfully: ' . ARCHIVE_NAME, 'SUCCESS');
logMessage('Archive size: ' . $archiveSizeFormatted, 'INFO');
logMessage('Archive path: ' . ARCHIVE_PATH, 'INFO');
// Count files in archive
$listCommand = sprintf('tar -tzf %s 2>/dev/null | wc -l', escapeshellarg(ARCHIVE_PATH));
$fileCount = trim(shell_exec($listCommand));
logMessage('Files compressed: ' . $fileCount, 'SUCCESS');
logMessage('Compression completed successfully!', 'SUCCESS');
// Display download link
echo "\n" . str_repeat('=', 50) . "\n";
echo "✓ COMPRESSION SUCCESSFUL\n";
echo str_repeat('=', 50) . "\n";
echo "Archive: " . ARCHIVE_NAME . "\n";
echo "Size: " . $archiveSizeFormatted . "\n";
echo "Files: " . $fileCount . "\n";
echo str_repeat('=', 50) . "\n";
} catch (Exception $e) {
logMessage('ERROR: ' . $e->getMessage(), 'ERROR');
echo "\n❌ COMPRESSION FAILED\n";
echo "Error: " . htmlspecialchars($e->getMessage()) . "\n";
exit(1);
}
// ============================================
// SYSTEM INFO (OPTIONAL)
// ============================================
echo "\n" . str_repeat('=', 50) . "\n";
echo "PHP SYSTEM INFORMATION\n";
echo str_repeat('=', 50) . "\n";
echo "PHP Version: " . phpversion() . "\n";
echo "OS: " . php_uname() . "\n";
echo "Memory Limit: " . ini_get('memory_limit') . "\n";
echo "Max Execution Time: " . ini_get('max_execution_time') . " seconds\n";
echo "Base Path: " . BASE_PATH . "\n";
echo str_repeat('=', 50) . "\n";
// Uncomment for full phpinfo():
// phpinfo();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment