Archive for July, 2010

Batch download in zip format

Dealing with files uploaded to the server, users might want to download the files in one zip file. So this snippet of code is the one that I have been using in my Zend Framework action:

$compressedFileName = 'download'.mktime().'.zip';
$currentFolderPath = '/data/';
$compressedFileLocation = '/tmp/'.$compressedFileName;
foreach ($files as $file) {
	$files_to_be_compressed[] = '"'.$file->getFileName().'"';
if (count($files_to_be_compressed)) {
	$command = "zip $compressedFileName " . implode(' ', $files_to_be_compressed);
//move the tar file to temp folder so that we can easily remove all the temp tar files with cron
	$command = "mv $compressedFileName $compressedFileLocation";
if (file_exists($compressedFileLocation))
	//disable the default layout because we want to present a file
	$documentMime = $docmans->mime_content_type($compressedFileLocation);
	// Since everything is correct, send the file then!
	header('Content-Description: File Transfer');
	header("Content-Type: $documentMime");
	header("Content-Length: ".filesize($compressedFileLocation));
	header("Content-Disposition: attachment; filename=\"$compressedFileName\"");
	header('Content-Transfer-Encoding: binary');
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');

This will only work in linux server, I guess.

Marking a machine as development machine

There are many times when I need to just run certain codes in the development machine or in the production machine. In order to do so, we can just check for the machine name:

if($_SERVER['SERVER_NAME'] == 'machine_name') {
  /run the codes inside here

But this is quite difficult when more than one development machine is involved because it will have different machine name. I have encountered cases when a certain code should only be run in production machine but because my test machine has different name, the code was run when I am testing the code.

Hence this piece of code that I encountered when I learnt about Zend Framework is quite useful for me:

if(getenv('APPLICATION_ENV') == 'development') {
  //run the codes inside here

Then just put this additional line to .htaccess file:

SetEnv APPLICATION_ENV development

All the development machines need to have the additional line in their .htaccess file.