質問

I have recently discovered ZipArchive for PHP, i have no problem adding files or files from strings however i have an image blob inside a MySQL database that i want to add to the ZipArchive. I can get the image in a separate file and i can also get it to download as a jpg. I want to be able to add the image into the archive.

The below code shows how i access my BLOB

header('Content-Type: image/jpg; charset=utf-8');


// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

$conB = mysql_connect("localhost", "user_name", "user_pass");//connect to the database
if (!$conB)
    {
        die('Could not connect: ' . mysql_error()); // if cannot connect then send error message
    }
mysql_select_db("binary", $conB); // define database name

$id = $_GET['ids'];

$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");   



while($row = mysql_fetch_array($query))
    {
        $content = $row['image'];

        header('Content-Disposition: attachment; filename=image"'.$row['ID'].'".jpg');

        fwrite($output, $content);
    }

That all works fine for me, the below code shows how i am adding a file to a zip archive

$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";

if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
    {
        echo "Cannot Open for writing";
    }


$zip->addEmptyDir('newFolder');

$zip->addFromString('text.txt', 'text file');

$zip->close();

//then send the headers to foce download the zip file

header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$ZipFileName"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

readfile($ZipFileName);

Does any one know how i can implement them together?

If you need any more information then i can provide it :)

役に立ちましたか?

解決

You can create the ZipArchive and then add the image(s) from a loop using addFromString() method. I use snippet from both your source codes below. The database connection logic is left out for simplicity reasons.

$zip = new ZipArchive();
$ZipFileName = "newZipFile.zip";

if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
    echo "Cannot Open for writing";
}


$zip->addEmptyDir('newFolder');

$query = mysql_query("SELECT * FROM tbl_images WHERE ID ='".$id."' ");   

while($row = mysql_fetch_array($query))
{
    $zip->addFromString( $row['image_name'],  $row['image']);
}

$zip->close();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top