I would like to gzip compress a file on my server using PHP. Does anyone have an example that would input a file and output a compressed file?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
The other answers here load the entire file into memory during compression, which will cause 'out of memory' errors on large files. The function below should be more reliable on large files as it reads and writes files in 512kb chunks.
This code does the trick
Simple one liner with gzencode():
If you are looking to just unzip a file, this works and doesn't cause issues with memory:
copy('file.txt', 'compress.zlib://' . 'file.txt.gz'); See documentation
It's probably obvious to many, but if any of the program execution functions is enabled on your system (
exec
,system
,shell_exec
), you can use them to simplygzip
the file.N.B.: Be sure to properly sanitize the
$filename
variable before using it, especially if it comes from user input (but not only). It may be used to run arbitrary commands, for example by containing something likemy-file.txt && anothercommand
(ormy-file.txt; anothercommand
).