Created
March 3, 2024 20:58
-
-
Save muathendirangu/9adfa749431507f5e7d544faa13740f3 to your computer and use it in GitHub Desktop.
a PHP script to compress, save and decompress data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define the data to be saved (replace with your actual data) | |
$data = array( | |
"name" => "John Doe", | |
"age" => 30, | |
"address" => array( | |
"street" => "123 Main St", | |
"city" => "Anytown", | |
"state" => "CA", | |
), | |
// Add more complex data structures as needed | |
); | |
// Filename for storing the compressed data | |
$filename = "data.txt.gz"; | |
// Function to compress and save data | |
function saveCompressedData($data, $filename) { | |
if (!is_writable(dirname($filename))) { | |
throw new Exception("Directory is not writable: " . dirname($filename)); | |
} | |
// Serialize the data | |
$serializedData = serialize($data); | |
// Compress the serialized data | |
$compressedData = gzcompress($serializedData, 9); // Adjust compression level if needed | |
// Open the file for writing in binary mode | |
$file = fopen($filename, "wb"); | |
// Write the compressed data to the file | |
fwrite($file, $compressedData); | |
// Close the file | |
fclose($file); | |
} | |
// Function to decompress and unserialize data | |
function loadCompressedData($filename) { | |
if (!file_exists($filename)) { | |
throw new Exception("File does not exist: " . $filename); | |
} | |
// Open the file for reading in binary mode | |
$file = fopen($filename, "rb"); | |
// Read the compressed data from the file | |
$compressedData = fread($file, filesize($filename)); | |
// Close the file | |
fclose($file); | |
// Decompress the data | |
$decompressedData = gzdecode($compressedData); | |
// Unserialize the decompressed data | |
$data = unserialize($decompressedData); | |
return $data; | |
} | |
try { | |
// Save the compressed data | |
saveCompressedData($data, $filename); | |
echo "Data saved successfully to: " . $filename . "\n"; | |
// Load the compressed data | |
$loadedData = loadCompressedData($filename); | |
// Verify the loaded data | |
if ($loadedData === $data) { | |
echo "Data loaded and verified successfully.\n"; | |
} else { | |
echo "Error: Loaded data does not match original data.\n"; | |
} | |
} catch (Exception $e) { | |
echo "Error: " . $e->getMessage(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment