1. <?php
  2. /**
  3. * Merges cookie datasets from staging environments.
  4. *
  5. * Usage: php merge_cookies.php --input-dir <input_directory> --output-file <output_file>
  6. */
  7. // Parse command line arguments
  8. $inputDir = isset($argv[1]) ? $argv[1] : null;
  9. $outputFile = isset($argv[2]) ? $argv[2] : 'merged_cookies.txt';
  10. if (!$inputDir || !$outputFile) {
  11. echo "Usage: php merge_cookies.php --input-dir <input_directory> --output-file <output_file>\n";
  12. exit(1);
  13. }
  14. // Validate input directory
  15. if (!is_dir($inputDir)) {
  16. echo "Error: Input directory '$inputDir' does not exist.\n";
  17. exit(1);
  18. }
  19. // Initialize an array to store cookie data
  20. $allCookies = [];
  21. // Iterate through files in the input directory
  22. $files = scandir($inputDir);
  23. foreach ($files as $file) {
  24. if ($file == '.' || $file == '..') {
  25. continue;
  26. }
  27. $filePath = $inputDir . '/' . $file;
  28. // Check if the file is a text file (assuming cookie data is in a simple text format)
  29. if (pathinfo($filePath, PATHINFO_EXTENSION) == 'txt') {
  30. $cookieData = file_get_contents($filePath);
  31. // Parse the cookie data from the file
  32. $cookies = parseCookieData($cookieData);
  33. if ($cookies) {
  34. $allCookies = array_merge($allCookies, $cookies);
  35. }
  36. }
  37. }
  38. // Write the merged cookie data to the output file
  39. if ($allCookies) {
  40. try {
  41. file_put_contents($outputFile, json_encode($allCookies));
  42. echo "Successfully merged cookies and saved to '$outputFile'.\n";
  43. } catch (Exception $e) {
  44. echo "Error writing to file: " . $e->getMessage() . "\n";
  45. exit(1);
  46. }
  47. } else {
  48. echo "No cookie data found in the input directory.\n";
  49. }
  50. /**
  51. * Parses cookie data from a text file.
  52. * Assumes each line in the file represents a cookie in the format:
  53. * name=value; name2=value2;
  54. *
  55. * @param string $data The cookie data as a string.
  56. * @return array An array of cookie data.
  57. */
  58. function parseCookieData(string $data): array
  59. {
  60. $cookies = [];
  61. $lines = explode(';', $data);
  62. foreach ($lines as $line) {
  63. $parts = explode('=', $line, 2); // Split into name and value
  64. if (count($parts) === 2) {
  65. $name = trim($parts[0]);
  66. $value = trim($parts[1]);
  67. $cookies[$name] = $value;
  68. }
  69. }
  70. return $cookies;
  71. }
  72. ?>

Add your comment