<?php
/**
* Backs up URL parameters to a specified directory.
* Includes basic sanity checks.
*
* @param string $backupDir The directory to store the backups.
* @param array $urlParams An associative array of URL parameters to backup.
* @return bool True on success, false on failure.
*/
function backupUrlParams(string $backupDir, array $urlParams): bool
{
// Sanity checks
if (!is_dir($backupDir)) {
error_log("Backup directory does not exist: " . $backupDir); // Log error
return false;
}
if (empty($urlParams)) {
error_log("No URL parameters provided."); // Log error
return false;
}
// Generate a unique backup filename
$timestamp = round(microtime(true));
$backupFilename = 'url_params_backup_' . $timestamp . '.txt';
$backupFilePath = $backupDir . '/' . $backupFilename;
try {
// Write URL parameters to file
$file = fopen($backupFilePath, 'w');
if ($file) {
foreach ($urlParams as $key => $value) {
if (is_string($value) || is_numeric($value)) { // Basic sanity check: string or number
fprintf($file, "%s=%s\n", $key, $value);
} else {
error_log("Skipping invalid value for parameter: " . $key . " (value: " . var_export($value, true) . ")"); //Log error
}
}
fclose($file);
return true;
} else {
error_log("Failed to open backup file for writing."); // Log error
return false;
}
} catch (Exception $e) {
error_log("Backup failed: " . $e->getMessage()); //Log error
return false;
}
}
// Example Usage (replace with your actual parameters and directory)
/*
$backupDirectory = '/path/to/your/backup/directory';
$urlParameters = [
'param1' => 'value1',
'param2' => 123,
'param3' => 'value3',
'param4' => true,
'param5' => ['a','b','c'] //Will be skipped
];
if (backupUrlParams($backupDirectory, $urlParameters)) {
echo "URL parameters backed up successfully!\n";
} else {
echo "Backup failed.\n";
}
*/
?>
Add your comment