Create a zip with ZipArchive getting files from s3 - php

right now I am creating the ZIP in this way, with the PDF files that are in the Storage 'invoices'. My goal is to move all these local files to the amazon s3 server. At the time of removing a file I have only had no problem, but at the time of generating the zip yes. How can I solve that? Thanks.
$pdfs = $request->get('check');
$public_dir = storage_path();
if (is_array($pdfs)) {
$zipname = "facturas" . time() . ".zip";
$zip = new \ZipArchive;
if ($zip->open($public_dir . '/app/invoices/' . $zipname, \ZipArchive::CREATE) === TRUE) {
foreach ($pdfs as $pdf) {
$zip->addFile(storage_path('app/invoices/' . $pdf), $pdf);
}
}
$zip->close();
$headers = array(
'Content-Type' => 'application/octet-stream',
);
$filetopath = $public_dir . '/app/invoices/' . $zipname;
if (file_exists($filetopath)) {
return response()->download($filetopath, $zipname, $headers);
}
}

Related

Can i display/open/preview base64 pdf without store in Laravel

Currently I am storing file into storage folder then show that file into browser and when close that file then remove that file from storage but I want directly show into browser and also can be download without store. This is working but storing file.
$fileFromAPI = $apiResponse->file;
$bin = base64_decode($fileFromAPI, true);
$path = config('pdf_paths.file') . $id . "/";
if (!is_dir($path)) {
$oldmask = umask(0);
Storage::makeDirectory($path, 0777, true);
umask($oldmask);
}
Storage::put($path . 'file_' . $fid . '.pdf', $bin);
$pdfread = 'storage/' . $path . 'file_' . $fid . '.pdf';
return response()->file($pdfread)->deleteFileAfterSend(true);
I found solution just set header and return it.
$fileFromAPI = $apiResponse->file;
$bin = base64_decode($fileFromAPI, true);
return response($bin)
->header('Content-Type', 'application/pdf');

I need to create .Zip file in Laravel and my code does not work

this is the 1st time I posted on StackOverflow. I need to create a zip file of multiple images. I've tried Zipper and also ZipArchive and my code still fails.
$zip = new \ZipArchive();
foreach ($students as $student) {
$download = 'album' . $student->album_id . '.zip';
if ($zip->open(public_path('albums/' . $student->album_id . '/' . $download), \ZipArchive::CREATE) === TRUE) {
$files = Storage::allFiles('public/albums/' . $student->album_id . '/image_files');
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
}
}
I can assure that all the images exist. I put the images in Storage/app/public/albums/$student->album_id/image_files/. Please help me.
First, you can add an additional step to verify that your file exists by using PHP built in function: file_exists()
Most times, if you your files do noT exists, no files will be added to the zip, and your code will run without throwing any error but still will not work.
What you're passing to addFile() is not a correct path. addFile() needs an absolute path to where your file is stored. You will need to add this line $file_path = storage_path("app/{$file}");
See code below:
$zip = new \ZipArchive();
foreach ($students as $student) {
$download = 'album' . $student->album_id . '.zip';
if ($zip->open(public_path('albums/' . $student->album_id . '/' . $download), \ZipArchive::CREATE) === TRUE) {
$files = Storage::allFiles('public/albums/' . $student->album_id . '/image_files');
foreach ($files as $file) {
$file_path = storage_path("app/{$file}");
if (file_exists($file_path)) {
$zip->addFile($filepath);
}
}
$zip->close();
}
}
Optionally, if you wish to download any of the zipped files, you can return the download response at the end of your code to download:
return response()->download(public_path('albums/' . $student->album_id . '/' . $download));

Can't create zip file (php)

So I found this class on the internet that can put files into a zip.
I have a form where I can upload pictures into a folder, then I tried to loop into these files and store them into a zip file but seems I failed somewhere.
zipper class
<?php
class zipper {
private $_files = array(),
$_zip;
public function __construct() {
$this->_zip = new ZipArchive;
}
public function add($input){
if(is_array($input)){
$this->_files = array_merge($this->_files, $input);
}else{
$this->_files[] = $input;
}
}
public function store($location = null){
if(count($this->_files) && $location){
foreach ($this->_files as $index => $file) {
if(!file_exists($file)){
unset($this->_files[$index]);
}
print_r($file . "<br>");// here gives me the exact path of the files.
}
if($this->_zip->open($location, file_exists($location) ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE)){
foreach ($this->_files as $file) {
$this->_zip->addFile($file, $file);
}
$this->_zip->close();
}
}
}
}
and this is my uploading file
> $uniqUser = uniqid(strtoupper($userName). "-" , true);
> $directory ='../upload/';
> $file_name is $files['name']
if(!is_dir("../upload/". $uniqUser ."/")) {
mkdir("../upload/". $uniqUser ."/");
}
if(move_uploaded_file($file_tmp, $directory . $uniqUser . "/" . $file_name)){
$uploaded[$position] = $directory . $uniqUser . "/" . $file_name;
$zipper = new zipper;
$zipper->add(BASE_URL . "/upload/" . $uniqUser . "/" . $file_name);
$zipper->store(BASE_URL . "/upload/" . $uniqUser . ".zip");
the last code is inside a foreach that loops into the files uploaded.
I don't know why I fail in creating the archive at the end ...
Could be an easy way to turn these new created folders into a zip or add them into a zip ?
First problem was because I added BASE_URL I had to write ../upload/.
Second problem was kinda stupid ...
I had to create the class outside the foreach $zipper = new zipper; and $zipper-store("../upload/" . $uniqUser . ".zip");for unnecessary repeating (added it at the bottom).

Symfony cannot open the downloaded zip file

I'm trying to make a zip file download. So I try to make the code like this :
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$zipFilePath = $root . '/' . $zipName;
// prepare BinaryFileResponse
$response = new BinaryFileResponse($zipFilePath);
$response->trustXSendfileTypeHeader();
$response->headers->set('Cache-Control', 'public');
$response->headers->set('Content-type', 'application/zip');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$zipName,
iconv('UTF-8', 'ASCII//TRANSLIT', $zipName)
);
return $response;
}
I think it was successful. But, when I tried to open the zip file, There is an error like this An error occurred while loading the archive.
then I tried to make the code like this
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
}
but I got nothing. The same thing also happen when i change it to this :
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header("HTTP/1.1 303"); // 303 is technically correct for this type of redirect
header("Location: http://{$_SERVER['HTTP_HOST']}/" . $fileName);
}
is there anyone who can help me to solve this download zip file problem?
An error occurred while loading the archive. occured in your clients side is because :
Your client doesn't have any application to open zip file.
zip file corrupt or missing extension.
There is possibility you never updated / fresh install. Try to
update it sudo apt-get update
Make sure your downloader app (like IDM or flareget) is working good. (I have problem with this, and when I disable the downloader app, it works) -By Asker
It is problem with client side, (connection or program error) or with the file it self. Try open the file using another PC.

Read Zip file from URL with PHP

I'm searching for a good solution to read a zip file from an url with php.
I checked the zip_open() function, but i never read anything about reading the file from another server.
Thank you very much
The best way to do that is to copy the remote file in a temporary one:
$file = 'http://remote/url/file.zip';
$newfile = 'tmp_file.zip';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
Then, you can do whatever you want with the temporary file:
$zip = new ZipArchive();
if ($zip->open($newFile, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
This is a basic example:
$url = 'https://my.domain.com/some_zip.zip?blah=1&hah=2';
$destination_dir = '/path/to/local/storage/directory/';
if (!is_dir($destination_dir)) {
mkdir($destination_dir, 0755, true);
}
$local_zip_file = basename(parse_url($url, PHP_URL_PATH)); // Will return only 'some_zip.zip'
if (!copy($url, $destination_dir . $local_zip_file)) {
die('Failed to copy Zip from ' . $url . ' to ' . ($destination_dir . $local_zip_file));
}
$zip = new ZipArchive();
if ($zip->open($destination_dir . $local_zip_file)) {
for ($i = 0; $i < $zip->numFiles; $i++) {
if ($zip->extractTo($destination_dir, array($zip->getNameIndex($i)))) {
echo 'File extracted to ' . $destination_dir . $zip->getNameIndex($i);
}
}
$zip->close();
// Clear zip from local storage:
unlink($destination_dir . $local_zip_file);
}
Download the file contents (possibly with file_get_contents, or copy to put it on your filesystem) then apply the unzip algorithm.

Categories