How to save encoded Base64 strings from database, to files, on disk?

1.2k Views Asked by At

First post:

I have a MySQL database, which is created by this command:

CREATE TABLE IF NOT EXISTSCKox(aTEXT NOT NULL,bTEXT NOT NULL );

Below is its structure:

+----------+-----------------+
|    id    |   base64_str    |
+----------+-----------------+
|  file_1  |  base64_str_1   |
|  file_2  |  base64_str_2   |
|  file_3  |  base64_str_3   |
|  file_4  |  base64_str_4   |
+----------+-----------------+

To save these Base64 strings (in database) to files (on my web server), I have run this PHP code:

<?php

    // database connection
    // ...

    $cmd = mysql_query("SELECT * FROM `MyTable`");
    while($data = mysql_fetch_array($cmd)) {

    $filename = $data[id];
    $filedata = $data[base64_str];

    header('Content-Description: File Transfer');
    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename= ".$filename."");

    echo base64_decode($filedata);

    }

    // ...

?>

It return only one file, and there is no data in this saved file. But, I want to save these Base64 strings to files, on server disk.


After getting some helps from people (on StackOverlow), I have updated my code, it is full:

// database connection
// ...

$cmd = mysql_query("SELECT * FROM `MyTable`");

while ($data = mysql_fetch_array($cmd)) {

file_put_contents($data['id'], base64_decode($data['base64_str']));
echo $data['base64_str'];

}

// ...

But, I still get one file only. What is the main problem? How to solve it?

2

There are 2 best solutions below

4
On

you cannot do that file send logic in a while, since you are sending the contents of the several files back to the client, and it will append all the files one after another, into one single file on client side.

You can either get all files, create temporary files in your server, compact them into a tgz, zip file or whatever and then send that back to the user, or you will only be able to send a single file.

This is also wrong:

$filename = $data[id];
$filedata = $data[base64_str];

You need quotes (single or double):

$filename = $data["id"];
$filedata = $data["base64_str"];
1
On

For dump files from db to disk use file_put_contents

$cmd = mysql_query("SELECT * FROM `MyTable`");

while ($data = mysql_fetch_array($cmd)) {
    file_put_contents($data['id'], base64_decode($data['base64_str']));
}