<?php
/**
* Merges cookie datasets from staging environments.
*
* Usage: php merge_cookies.php --input-dir <input_directory> --output-file <output_file>
*/
// Parse command line arguments
$inputDir = isset($argv[1]) ? $argv[1] : null;
$outputFile = isset($argv[2]) ? $argv[2] : 'merged_cookies.txt';
if (!$inputDir || !$outputFile) {
echo "Usage: php merge_cookies.php --input-dir <input_directory> --output-file <output_file>\n";
exit(1);
}
// Validate input directory
if (!is_dir($inputDir)) {
echo "Error: Input directory '$inputDir' does not exist.\n";
exit(1);
}
// Initialize an array to store cookie data
$allCookies = [];
// Iterate through files in the input directory
$files = scandir($inputDir);
foreach ($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$filePath = $inputDir . '/' . $file;
// Check if the file is a text file (assuming cookie data is in a simple text format)
if (pathinfo($filePath, PATHINFO_EXTENSION) == 'txt') {
$cookieData = file_get_contents($filePath);
// Parse the cookie data from the file
$cookies = parseCookieData($cookieData);
if ($cookies) {
$allCookies = array_merge($allCookies, $cookies);
}
}
}
// Write the merged cookie data to the output file
if ($allCookies) {
try {
file_put_contents($outputFile, json_encode($allCookies));
echo "Successfully merged cookies and saved to '$outputFile'.\n";
} catch (Exception $e) {
echo "Error writing to file: " . $e->getMessage() . "\n";
exit(1);
}
} else {
echo "No cookie data found in the input directory.\n";
}
/**
* Parses cookie data from a text file.
* Assumes each line in the file represents a cookie in the format:
* name=value; name2=value2;
*
* @param string $data The cookie data as a string.
* @return array An array of cookie data.
*/
function parseCookieData(string $data): array
{
$cookies = [];
$lines = explode(';', $data);
foreach ($lines as $line) {
$parts = explode('=', $line, 2); // Split into name and value
if (count($parts) === 2) {
$name = trim($parts[0]);
$value = trim($parts[1]);
$cookies[$name] = $value;
}
}
return $cookies;
}
?>
Add your comment