Solved

Php Zip an image

Posted on 2011-09-21
26
308 Views
Last Modified: 2012-05-12
hi,
Just wondering why when i use this piece of code i get 0kb when i exported the zip.
Paths of the images are all correct, and the when echoed plus it does not fail on "file_exists() "

Can any suggest some debugging solutions to get this going? or if someone can take a quick look at this code and see what wrong?


    public function createImageZip(){    
                                        
        $concept = $_POST['concept'];

        if(empty($concept))
            return false;
            
        $zipper = new ZipArchive();
        
        $fileName = 'export_'.time().'.zip';
                          
        $rez = $zipper->open(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName, ZipArchive::CREATE);
    
       if($rez !== true)
            return false;                            
            
        foreach($concept as $key=>$value){
            if(intval($value) > 0){
                $query = "SELECT
                            `df_concept_image`
                          FROM
                            `df_concept`
                          WHERE
                            `df_concept_id` = '".intval($key)."'
                          LIMIT 1
                          ";
                $image = getRow($query);     

				
                if(file_exists(DF_PROJECT_IMAGE_FOLDER.'/'.$image['df_concept_image'])){
     
					
					 $zipper->addFile(DF_PROJECT_IMAGE_FOLDER, $image['df_concept_image']); 
		
				}
            }
        }
		$zipper->close(); 	
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=export_concept_images.zip;" );
        header("Content-Transfer-Encoding: binary");
		
		
        header("Content-Length: ".filesize(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName));
        readfile(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
        @unlink(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
		
		
        return true;
    }
    

Open in new window


Cheers,
Chi
0
Comment
Question by:chiboy888
  • 11
  • 11
  • 2
  • +1
26 Comments
 
LVL 13

Expert Comment

by:dsmile
Comment Utility
1. comment out all header() to see if readfile() can really read your zip to screen (in binary code ofcourse)
2. if it CAN then uncomment and remove return true; on line 53 then try again
0
 

Author Comment

by:chiboy888
Comment Utility
Hi dsmile,
i commented out lines 39 to 53 and it returns a blank page.
i commented out just the headers returns a blank page.
I commented out just the return, returns a blank page.

any other suggestions?

Chi
0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
I think your problem is in this line:
$zipper->addFile(DF_PROJECT_IMAGE_FOLDER, $image['df_concept_image']);

Open in new window


I believe it should be:
$zipper->addFile(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image']), $image['df_concept_image']);

Open in new window


Looks to me like you are trying to add the source folder when you meant to add the image file only.
0
 

Author Comment

by:chiboy888
Comment Utility
hi mykde,
I have tried that and it still gives me a 0kb. the images and dir i believe are definitely correct because it does not throw a error in the if(file_exists(DF_PROJECT_IMAGE_FOLDER.'/'.$image['df_concept_image']))

any other suggestions?

chi
0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
Well for debuging I would start with this:

commented out lines 39 to 53
Replace line 30 with:
var_dump($image);
            if (file_exists(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'])) {
            echo '<br /><img src="'.DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'] . '" alt="' . $image['df_concept_image'] . '"><br /><br />';

Open in new window


This will allow you to verify the response from the query and verify that the images are where you think they should be.
0
 

Author Comment

by:chiboy888
Comment Utility
i got
array(1) { ["df_concept_image"]=> string(7) "288.jpg" }
288.jpg

Open in new window


which is the correct image. but was this meant to display the image?

0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
Yes that should have displayed the image on the page.

Will you attach the full page source from this test
0
 
LVL 13

Expert Comment

by:dsmile
Comment Utility
@Chi: you should only comment out line 39- to 48, since we need to assure that line 49 could print out some file content.
If this still returns blank page, then try to echo something to see if it works.

Eg:

 echo 'SOMETHING SHOULD DISPLAY';
 readfile(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);


If it still shows blank page then may be you encouter this:
1. there's some error above
2. display error is set to  (means no error should be displayed) --> try to add these lines at the first line of the file

ini_set('display_errors', 'On');
error_reporting(E_ALL ^ E_NOTICE);
0
 

Author Comment

by:chiboy888
Comment Utility
@myde and dsmile the source is
array(1) {
  ["df_concept_image"]=>
  string(7) "288.jpg"
}
<br /><img src="C:\inetpub\vhosts\testdb.directionfirst.com/uploads/df/projects/288.jpg" alt="288.jpg"><br /><br />SOMETHING SHOULD DISPLAY¿¿¿¿...more binary code...	

Open in new window


@dsmile: i put the code in

I think it was looking into a different folder which had no images, i then placed the images inside this folder and i got the above code.

I then took out the code from before, and tested, now i get 1kb zip, but when i try to extract the zip i get "Can not open file 'xxxx\export_concept_images.zip' as archive.

i think we are getting close to solve this...any other suggestions?

chi

0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
The reason that the zip file is not opening is due to the text that is not in the source from the debugging.

Remove or comment out the elements that we added for debugging.

You can also open the zip file with a text editor(notepad, wordpad, notepad++) and you should be able to see the extra clear test that is being included (effectively corrupting the archive)
0
 

Author Comment

by:chiboy888
Comment Utility
hi mykde,
I commented out all the code that was inserted before and i uncomment out lines 39 and 38
i now have
          if (file_exists(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'])) {
$zipper->addFile(DF_PROJECT_IMAGE_FOLDER.'/'.$image['df_concept_image'], $image['df_concept_image']); }			

Open in new window

but now i get 0kb again...is there something wrong with  $fileName = 'export_'.time().'.zip'; and
 readfile(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
  @unlink(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);




0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
Try adding exit; after readfile():

readfile(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
exit;
@unlink(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);

Open in new window

I think that the unlink() is causing the issue.
0
 

Author Comment

by:chiboy888
Comment Utility
Unfortunately its still giving me 0kb, below is the code that im using
    public function createImageZip(){    
                                        
        $concept = $_POST['concept'];
        $flag = 0;
        if(empty($concept))
            return false;
            
        $zipper = new ZipArchive();
        
        $fileName = 'export_'.time().'.zip';
                          
        $rez = $zipper->open(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName, ZipArchive::CREATE);
    
       if($rez !== true)
            return false;                            
            
        foreach($concept as $key=>$value){
            if(intval($value) > 0){
                $query = "SELECT
                            `df_concept_image`
                          FROM
                            `df_concept`
                          WHERE
                            `df_concept_id` = '".intval($key)."'
                          LIMIT 1
                          ";
                $image = getRow($query);     
      
            if (file_exists(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'])) {
     
				$zipper->addFile(DF_PROJECT_IMAGE_FOLDER.'/'.$image['df_concept_image'], $image['df_concept_image']); 
				
		
				}
            } 
        }
		
		
		$zipper->close(); 	

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=export_concept_images.zip;" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName));
        readfile(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
		exit;
        @unlink(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName);
		
		
       return true;

    }

Open in new window

0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 3

Expert Comment

by:mykde
Comment Utility
Maybe the problem is Apache is trying to compress the output, so try adding this to the top of the page:
@apache_setenv('no-gzip', 1); 
@ini_set('zlib.output_compression', 0);
 

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Never zip an image file.  It is not worth the effort.  Just send the image in its original form.

In fact, at current network speeds, the time you save in data transmission by zipping files is more than lost at the other end when your recipient finds that they cannot just open the file, but they have to unzip the file first.

Avoiding zip will make your programming easier and make your clients happier, trust me!
0
 

Author Comment

by:chiboy888
Comment Utility
@ Ray,
The only reason we want to zip the image because, its a set of images. the user will click on check boxes next to an image which then looks them up in a query returning the images. It would be messy trying to download them 1 at a time.

@mykde, when i put that in my code it gives me a 500 error internal error.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Check boxes and image file names are completely unrelated to the question of Zip compression.  Please consider redesigning the application to use a more modern and well-considered design pattern.
0
 

Author Comment

by:chiboy888
Comment Utility
hi Ray,
Redesigning the application is not an option.
we just need to find a way to zip a group of files(images) into 1 download.
0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
Sorry I assumed you were on an apache server.

but now I see its IIS

so only use this:
@ini_set('zlib.output_compression', 0);

Open in new window


I have two other ideas.

Idea 1: replace line 48 with:
header("Content-Length: " . filesize( realpath(DF_ARCHIVE_TEMP_FOLDER . '/' . $fileName)));

Open in new window


Idea 2: Remove line 48
This is a bit of a hacky fix as it will not allow the browser to display a progress bar as the file downloads.
0
 

Author Comment

by:chiboy888
Comment Utility
hi mykde,
both ideas just outputed 0kb.... :(
0
 

Author Comment

by:chiboy888
Comment Utility
by the way does
        $zipper = new ZipArchive();
        
        $fileName = 'export_'.time().'.zip';
                          
        $rez = $zipper->open(DF_ARCHIVE_TEMP_FOLDER.'/'.$fileName, ZipArchive::CREATE);

Open in new window

mean to create a zip ? ive checked this folder and there is nothing in there....or is this just some kind of temp zip ?
0
 
LVL 3

Accepted Solution

by:
mykde earned 250 total points
Comment Utility
Yeah it must be something to do with the server configuration,

I made this on my local box and it works prefectly

<?php
 
define('DF_ARCHIVE_TEMP_FOLDER', realpath("."));
define('DF_PROJECT_IMAGE_FOLDER', realpath("."));

function createImageZip() {

    $concept = array(1, 2, 3);
    $flag = 0;
    if (empty($concept))
        return false;

    $zipper = new ZipArchive();

    $fileName = 'export_' . time() . '.zip';

    $rez = $zipper->open(DF_ARCHIVE_TEMP_FOLDER . '/' . $fileName, ZipArchive::CREATE);

    if ($rez !== true)
        return false;

    foreach ($concept as $key => $value) {
        if (intval($value) > 0) {

            $image = array('df_concept_image' => 'image_1.jpg');

            if (file_exists(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'])) {

                $zipper->addFile(DF_PROJECT_IMAGE_FOLDER . '/' . $image['df_concept_image'], "image" . $key . ".jpg");
            }
        }
    }

    $zipper->close();

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=export_concept_images.zip;");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize(DF_ARCHIVE_TEMP_FOLDER . '/' . $fileName));


    readfile(DF_ARCHIVE_TEMP_FOLDER . '/' . $fileName);
    @unlink(DF_ARCHIVE_TEMP_FOLDER . '/' . $fileName);

    return true;
}

createImageZip();

Open in new window

0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
yes that should be making created a fix there.

Try replacing all DF_ARCHIVE_TEMP_FOLDER with realpath('.') everywhere it is used in the function.
0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
wow the first sentance in that last post I posted is hideous. :(

It should read "Yes, that line should be creating a zip file in that location"
0
 

Author Comment

by:chiboy888
Comment Utility
omg...i just checked the folder and the permission wasn't set correctly. as we moved this to a different location, i guess the permissions didn't follow.
WOOOT WOOOH...thanks for your effort mykde
0
 
LVL 3

Expert Comment

by:mykde
Comment Utility
Nice :)
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Often people are aiming at development of perfect Magento websites. Though, it is easier said than done. You know what’s much easier? To ruin everything. It can be done in seconds. Many of us experimented with design, tried to change some values dir…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now