Download zip file laravel 5.2 - php

Gettin this error when im trying to download zip file
The file "C:\wamp\www\Petro\public\download/downloads.zip" does not exist
My code
if (\File::exists('download/downloads.zip')) {
$directory = public_path('download');
$success = \File::cleanDirectory($directory);
foreach($checked as $check){
$path = File::where('name',$check)->select('real_path')->first();
$img = \Image::make($path->real_path);
$img->save(public_path('download'). '/'. $check);
}
} else {
foreach($checked as $check){
$path = File::where('name',$check)->select('real_path')->first();
$img = \Image::make($path->real_path);
$img->save(public_path('download'). '/'. $check);
}
}
$files = \File::files('download');
\Zipper::make('download/downloads.zip')->add($files);
$pathtoFile = public_path('download/downloads.zip');
return response()->download($pathtoFile);
The zip is created but i cant download it, what is wrong with my code?
When i use dd($files) after create the zip :
array:4 [▼
0 => "download/batman.jpg"
1 => "download/batmanfamily.jpg"
2 => "download/batwoman.jpg"
3 => "download/daredevil.jpg"
]
There is not zip file but if i check in my local directory the zip is created.
Can you guys give me a hand with this and sorry for the bad english.

As you can see in your error you have / instead of \ this.
The file "C:\wamp\www\Petro\public\download/downloads.zip" does not exist
^
Here
change / in following line to \:
$pathtoFile = public_path('download/downloads.zip');
To
$pathtoFile = public_path('download\downloads.zip');

You need to close the process.
Zipper::make('download/downloads.zip')->add($files)->close();

Related

Download a zip file that is created when a URL is passed to domain site, but I have tried for 4 days 30-50 different ways, and no luck. CAISO OASIS

The site is the CAISO OASIS and they use an old way of querying and returning datasets. 30 days at a time, zip file with enclosed *.csv files. I have tried for 4 days coming up with a way to automate this download first of the zip file but i cant even get past there.
If I populate the url string I want and enter it myself in the address bar a zip file will start downloading, I cannot for the life of me get it to do the same through code.
I need to use php to accomplish this task.
I have tried, fopen, file_get_contents, file_put_contents, cURL, ziparchive class. I have tried changing all sorts of things. The best I get is a download of a corrupt zip file that is empty.
Ideally i would love to extract the *.csv or xml file but I cannot even do the first basic step.
The following variable I populate, $url_caiso_qry, if you take the echo string and past in the browser and enter the zip file will start downloading, but I cannot download it automatically.
http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1
<?php
$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);
// creates data array for precio de carga SIN
// function create_dataarrayp_chrt($zona) {
$ayer = date("Ymd\T7:00-0000", strtotime('now - 1 day'));
$mespasado = date("Ymd\T7:00-0000",strtotime('-30 days'));
$sdate = $mespasado; //startdatetime=
$edate = $ayer; //enddatetime=
$resultformat = '6';
$queryname='SLD_FCST';
$version='1';
$marketrunid='ACTUAL';
$fields = [
'startdatetime' => $sdate,
'enddatetime' => $edate,
'resultformat' => $resultformat,
'queryname' => $queryname,
'market_run_id' => $marketrunid,
'version' => $version,
];
//post fields
$postparam = urldecode(http_build_query($fields));
//PRECIOS url base string
$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?';
//$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?resultformat=6&queryname=SLD_FCST&version=1&market_run_id=ACTUAL&startdatetime=' . $sdate . 'T07:00-0000&enddatetime=' . $edate . 'T07:00-0000';
$url_caiso_qry = $urlcaiso . $postparam;
$caisofile = file_get_contents($url_caiso_qry, "rb");
//attempt to write file to destination path, but no file is written. Instead the following warning
//Warning: file_put_contents(/name1/name2/private/test/):
// failed to open stream: No such file or directory in C:\xampp\htdocs\name1\name2\private\test.php on line 94
$destination_path = WWW_ROOT . 'name2/private/test/';
$newfile = file_put_contents($destination_path, $caisofile);
echo $newfile . '<br><br>';
?>
The second parameter you pass to file_get_contents describes the use_include_path according to the php documentation.
I tried this simple example to get the file and save it:
<?php
$content = file_get_contents('http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1');
file_put_contents('example.zip', $content);
Running file example.zip gives the following output:
example.zip: Zip archive data, at least v2.0 to extract which indicates success.
So essentially your final code could look something like this:
<?php
// Build url here
$url = 'http://oasis.caiso.com/...';
// Download file
$zipFile = file_get_contents($url);
$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);
$targetPath = WWW_ROOT . 'proj3-ampenergy/private/test/'; // This could be any other path where your file should be stored
// Write contents to file
file_put_contents($targetPath, $zipFile);
// Write extraction logic here
Clean & tested code. Your csv file will be extracted to your script's directory.
<?php
define('PATH_ZIP', __DIR__ . '/archive.zip');
$url = 'http://oasis.caiso.com/oasisapi/SingleZip?' . http_build_query
([
'startdatetime' => '20220109T7:00-0000',
'enddatetime' => '20220207T7:00-0000',
'resultformat' => '6',
'queryname' => 'SLD_FCST',
'market_run_id' => 'ACTUAL',
'version' => '1',
]);
$data = file_get_contents($url);
file_put_contents(PATH_ZIP, $data);
$zip = new ZipArchive;
if ($zip->open(PATH_ZIP) === true)
{
$zip->extractTo(__DIR__);
$zip->close();
}

how to unzip .zip file in codeigniter 4 (PHP)

I am trying to extract zip file in codeigniter 4... I have the code below
$file_name = session()->get('file_name');
// Zip file name
$filename = "/public/$file_name";
$zip = new \ZipArchive;
$res = $zip->open($filename);
if ($res === true) {
// Unzip path
$path = "/public";
// Extract file
$zip->extractTo($path);
$zip->close();
return 'Site Updated Successfully';
} else {
return "failed to update $filename!";
}
}
but I get this result: return "failed to update $filename!";
Please can someone help me fix the issue with the code.
This has nothing specifically to do with Codeigniter. It's just using PHP and ZipArchive. The code looks OK - be sure the file is really in the /public/ directory and that it is a zip archive. The PHP site has examples that are like $zip = new ZipArchive; (without the \ char); maybe try that.

How to copy an image from one folder to another using php

I'm having difficulty in copying an image from one folder to another, now i have seen many articles and questions regarding this, none of them makes sense or work, i have also used copy function but its giving me an error. " failed to open stream: No such file or directory" i think the copy function is only for files. The image i wanna copy is present in the root directory. Can anybody help me please. What i am doing wrong here or is there any other way???
<?php
$pic="somepic.jpg";
copy($pic,'test/Uploads');
?>
You should write your code same as below :
<?php
$imagePath = "/var/www/projectName/Images/somepic.jpg";
$newPath = "/test/Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
You should have file name in destination like:
copy($pic,'test/Uploads/'.$pic);
For your code, it must be like this:
$pic="somepic.jpg";
copy($pic,'test/Uploads/'.$pic);
Or use function, like this:
$pic="somepic.jpg";
copy_files($pic,'test/Uploads');
function copy_files($file_path, $dest_path){
if (strpos($file_path, '/') !== false) {
$pathinfo = pathinfo($file_path);
$dest_path = str_replace($pathinfo['dirname'], $dest_path, $file_path);
}else{
$dest_path = $dest_path.'/'.$file_path;
}
return copy($pic, $dest_path);
}

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

Linux PHP ExtractTo returns whole path instead of the file structure

I am pulling my hair out over here. I have spent the last week trying to figure out why the ZipArchive extractTo method behaves differently on linux than on our test server (WAMP).
Below is the most basic example of the problem. I simply need to extract a zip that has the following structure:
my-zip-file.zip
-username01
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
-username02
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
The following code will extract the root zip file and keep the structure on my WAMP server. I do not need to worry about extracting the subfolders yet.
<?php
if(isset($_FILES["zip_file"]["name"])) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$errors = array();
$name = explode(".", $filename);
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$errors[] = "The file you are trying to upload is not a .zip file. Please try again.";
}
$zip = new ZipArchive();
if($zip->open($source) === FALSE)
{
$errors[]= "Failed to open zip file.";
}
if(empty($errors))
{
$zip->extractTo("./uploads");
$zip->close();
$errors[] = "Zip file successfully extracted! <br />";
}
}
?>
The output from the script above on WAMP extracts it correctly (keeping the file structure).
When I run this on our live server the output looks like this:
--username01\filename01.txt
--username01\images.zip
--username01\songs.zip
--username02\filename01.txt
--username02\images.zip
--username02\songs.zip
I cannot figure out why it behaves differently on the live server. Any help will be GREATLY appreciated!
To fix the file paths you can iterate over all extracted files and move them.
Supposing inside your loop over all extracted files you have a variable $source containing the file path (e.g. username01\filename01.txt) you can do the following:
// Get a string with the correct file path
$target = str_replace('\\', '/', $source);
// Create the directory structure to hold the new file
$dir = dirname($target);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Move the file to the correct path.
rename($source, $target);
Edit
You should check for a backslash in the file name before executing the logic above. With the iterator, your code should look something like this:
// Assuming the same directory in your code sample.
$dir = new DirectoryIterator('./uploads');
foreach ($dir as $fileinfo) {
if (
$fileinfo->isFile()
&& strpos($fileinfo->getFilename(), '\\') !== false // Checking for a backslash
) {
$source = $fileinfo->getPathname();
// Do the magic, A.K.A. paste the code above
}
}

Categories