[eluser]Unknown[/eluser]
Hello everyone,
I was looking into the ZIP library as I wanted my users to be able to download several files at once on my site, the library works perfectly (as most CI stuff do) but I had a little problem: The file had their unique name that I use to make sure I can find them in the DB.What I wanted to do is rename the files with their original name before I put them in the Zip.
I added this function to the zip library:
Code:
function rename_and_read_file($path, $new_name, $preserve_filepath = FALSE)
{
if ( ! file_exists($path))
{
return FALSE;
}
if (FALSE !== ($data = file_get_contents($path)))
{
$full_path_with_name = str_replace("\\", "/", $path);
$path_only = dirname($full_path_with_name);
$new_name = $path_only.'/'.$new_name;
if ($preserve_filepath === FALSE)
{
$new_name = preg_replace("|.*/(.+)|", "\\1", $new_name);
}
$this->add_data($new_name, $data);
return TRUE;
}
return FALSE;
}
I'm sure this could be optimized but as is it does the job.
In my controller I use:
Code:
function download_bulk($file_ids)
{
foreach($file_ids as $file_id)
{
if ($full_path_to_file = $this->files_model->find_file($file_id,$this->user_id))
{
$real_file_name = $this->files_model->get_full_filename($file_id);
$this->zip->rename_and_read_file($full_path_to_file,$real_file_name);
}
}
$this->zip->download('My_files.zip');
redirect('home'); //or where ever you want to..
}
As you can imagine (I'll spare the code for those as they depend on your implementation)
- the find_file(file_id,user_id) return the full path to the file as it is on the disk (with its unique name) or false if the file cannot be found (or you don't have ownership)
- the get_full_filename($file_id) is my files_model returns the originial name as a string like: myfile.pdf
- the $this->user_id is because I create a global variable in the class so I don't have to read the session user_id all the time. Don't know if it is worth it though in terms of performance.
I hope this helps. I'm open to comments and improvement on this.. For example I wonder if there is a smart way to check if two of the files have original name.. what happens when they are both put in the Zip then..
Cheers
Antony