1. <?php
  2. /**
  3. * Backs up URL parameters to a specified directory.
  4. * Includes basic sanity checks.
  5. *
  6. * @param string $backupDir The directory to store the backups.
  7. * @param array $urlParams An associative array of URL parameters to backup.
  8. * @return bool True on success, false on failure.
  9. */
  10. function backupUrlParams(string $backupDir, array $urlParams): bool
  11. {
  12. // Sanity checks
  13. if (!is_dir($backupDir)) {
  14. error_log("Backup directory does not exist: " . $backupDir); // Log error
  15. return false;
  16. }
  17. if (empty($urlParams)) {
  18. error_log("No URL parameters provided."); // Log error
  19. return false;
  20. }
  21. // Generate a unique backup filename
  22. $timestamp = round(microtime(true));
  23. $backupFilename = 'url_params_backup_' . $timestamp . '.txt';
  24. $backupFilePath = $backupDir . '/' . $backupFilename;
  25. try {
  26. // Write URL parameters to file
  27. $file = fopen($backupFilePath, 'w');
  28. if ($file) {
  29. foreach ($urlParams as $key => $value) {
  30. if (is_string($value) || is_numeric($value)) { // Basic sanity check: string or number
  31. fprintf($file, "%s=%s\n", $key, $value);
  32. } else {
  33. error_log("Skipping invalid value for parameter: " . $key . " (value: " . var_export($value, true) . ")"); //Log error
  34. }
  35. }
  36. fclose($file);
  37. return true;
  38. } else {
  39. error_log("Failed to open backup file for writing."); // Log error
  40. return false;
  41. }
  42. } catch (Exception $e) {
  43. error_log("Backup failed: " . $e->getMessage()); //Log error
  44. return false;
  45. }
  46. }
  47. // Example Usage (replace with your actual parameters and directory)
  48. /*
  49. $backupDirectory = '/path/to/your/backup/directory';
  50. $urlParameters = [
  51. 'param1' => 'value1',
  52. 'param2' => 123,
  53. 'param3' => 'value3',
  54. 'param4' => true,
  55. 'param5' => ['a','b','c'] //Will be skipped
  56. ];
  57. if (backupUrlParams($backupDirectory, $urlParameters)) {
  58. echo "URL parameters backed up successfully!\n";
  59. } else {
  60. echo "Backup failed.\n";
  61. }
  62. */
  63. ?>

Add your comment