What are the advantages of compressing files before downloading them from a server in terms of traffic and efficiency?

When downloading files from a server, compressing them before transfer can significantly reduce the amount of data being sent over the network. This can lead to faster download speeds, lower bandwidth usage, and improved overall efficiency. Compressing files can also help save storage space on both the server and the client side.

<?php
// Function to compress a file before downloading
function compressFile($source, $destination, $compression_level = 9) {
    $file = file_get_contents($source);
    $compressed = gzencode($file, $compression_level);
    file_put_contents($destination, $compressed);
}

// Example usage
$source_file = 'example.txt';
$compressed_file = 'example.txt.gz';
compressFile($source_file, $compressed_file);
?>