Compress a local php file before saving it to the database

I want to compress a file in php before sending it to db.

One solution

$statement = $pdo->prepare('INSERT INTO test(datablob) VALUES(?);');
$data = gzcompress(file_get_contents('file.txt'));
$statement->bindParam(1,$data,PDO::PARAM_LOB);
$statement->execute();

But I do not want to read the file in memory. Without compression, it will look like this:

$statement = $pdo->prepare('INSERT INTO test(datablob) VALUES(?);');
$data = fopen('file.txt');
$statement->bindParam(1,$data,PDO::PARAM_LOB);
$statement->execute();

How to compress a local accessible file in php to add it to the database (without storing the contents in memory)?

I’m thinking about the decision to wrap the Stream file in a compression stream and bind this “compressed” stream to a PDO instruction. But what will it look like?

+4
source share
1 answer

I found an easy solution with PHP / stream_filters:

$statement = $pdo->prepare('INSERT INTO test(datablob) VALUES(?);');
$data = fopen('file.txt','rb');
stream_filter_append($data,'zlib.deflate',STREAM_FILTER_READ);
$statement->bindParam(1,$data,PDO::PARAM_LOB);
$statement->execute();
+3
source

Source: https://habr.com/ru/post/1687308/


All Articles