Skip to content

Instantly share code, notes, and snippets.

@lazarospsa
Last active April 1, 2023 17:45
Show Gist options
  • Save lazarospsa/1358676fc862670e0b811b36e5246c0a to your computer and use it in GitHub Desktop.
Save lazarospsa/1358676fc862670e0b811b36e5246c0a to your computer and use it in GitHub Desktop.
PHP compress file without library
function compress_file($input_file, $output_file) {
// Open the input file for reading
$input_handle = fopen($input_file, 'rb');
if (!$input_handle) {
echo "Failed to open input file\n";
return;
}
// Open the output file for writing
$output_handle = fopen($output_file, 'wb');
if (!$output_handle) {
echo "Failed to open output file\n";
return;
}
// Read the input file into a buffer
$input_buffer = file_get_contents($input_file);
// Compress the input buffer using RLE
$output_buffer = '';
$current_byte = $input_buffer[0];
$count = 1;
for ($i = 1; $i < strlen($input_buffer); $i++) {
if ($input_buffer[$i] === $current_byte && $count < 255) {
$count++;
} else {
$output_buffer .= chr($count) . $current_byte;
$current_byte = $input_buffer[$i];
$count = 1;
}
}
$output_buffer .= chr($count) . $current_byte;
// Write the compressed buffer to the output file
fwrite($output_handle, $output_buffer);
// Close the input and output files
fclose($input_handle);
fclose($output_handle);
}
// Compress a file
compress_file('input.bin', 'output.bin');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment