Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Php Zip an image

Posted on 2011-09-21
26
322 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
ID: 36577973
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
ID: 36578034
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
ID: 36578165
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:chiboy888
ID: 36578180
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
ID: 36578245
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
ID: 36578265
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
ID: 36578367
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
ID: 36578401
@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
ID: 36578539
@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
ID: 36578563
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
ID: 36578702
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
ID: 36578791
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
ID: 36578806
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
 
LVL 3

Expert Comment

by:mykde
ID: 36578917
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 109

Expert Comment

by:Ray Paseur
ID: 36583974
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
ID: 36584347
@ 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 109

Expert Comment

by:Ray Paseur
ID: 36584497
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
ID: 36584587
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
ID: 36584903
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
ID: 36584942
hi mykde,
both ideas just outputed 0kb.... :(
0
 

Author Comment

by:chiboy888
ID: 36584950
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
ID: 36584957
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
ID: 36584967
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
ID: 36584972
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
ID: 36584981
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
ID: 36584988
Nice :)
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This article discusses four methods for overlaying images in a container on a web page
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
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 …

856 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