I am trying to extract a zip-file using a wildcard. The point of this is to find out the said file. The file has a changing name after today's date when I download it: test-18-02-2016.zip. I tried like this:
<?php
$myFile = 'C:/Users/Acer/Downloads/test*.zip';
$zip = new ZipArchive();
if($zip->open($myFile) === true) {
$zip->extractTo('C:/Users/Acer/Downloads/');
$zip->close();
echo 'ok';
} else {
echo 'NOT ok!';
}
I am getting NOT ok ..of course, but when i switch on to test-18-02-2016.zipI get ok.
Any help to figure out why and how to resolve this is very appreciate it.
A ZipArchive can only represent one file at a time. If you absolutely must use wildcards, consider passing the wildcard string into glob() and using the results it returns.
For example:
$myFileList = glob('C:/Users/Acer/Downloads/test*.zip');
foreach ($myFileList as $myFile) {
echo 'Unzipping ' . $myFile . PHP_EOL;
$zip = new ZipArchive();
if($zip->open($myFile) === true) {
$zip->extractTo('C:/Users/Acer/Downloads/');
$zip->close();
echo 'ok';
} else {
echo 'NOT ok!';
}
}
I don't see anything in the documentation that says ZipArchive->open accepts a wildcard path in this way. Besides, what would happen if several files matched?
Instead, find the file you want. If it's today's date...
$myFile = 'C:/Users/Acer/Downloads/test-'.date("d-m-Y").'.zip';
Related
This will be simple for someone, so hope you don't mind my asking here, I have some php code like so:
<?php
$zip = new ZipArchive;
if ($zip->open('myfiles1.zip) === TRUE) {
$zip->addFile('readme.txt', 'readme.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
I would like to make it recurse through the directory it is in and add the same file "readme.txt" to all the zips inside it.
I'm trying to create a script that will send across files from one server to another. My script successfully does that as well as checks if the file has something in it or not. My next step is to check whether the file already exists on the server; if the file already exists it does not send and if it does not exist, it does send.
I've tried a few different things and can't seem to get my head around it. How can I get it to check whether the file already exists or not? Any help would be appreciated!
(I had a look at some similar questions but couldn't find anything specific to my issue.)
require('constants.php');
$files = $sftp->nlist('out/');
foreach($files as $file) {
if(basename((string) $file)) {
if(strpos($file,".") > 1) { //Checks if file
$filesize = $sftp->size('out/'.$file); //gets filesize
if($filesize > 1){
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
else {
$sftp->get('out/'.$file, 'import/'.$file); //Sends file over
//$sftp->delete('out/'.$file); //Deletes file from out folder
}
else {
echo $file. ' is empty.</br>';
}
}
}
}
}
EDIT: To try and get this to work, I wrote the following if statement to see if it was finding the file test.php;
if (file_exists('test.txt')){
echo 'True';
} else {
echo 'False';
}
This returned true (a good start) but as soon as I put this into my code, I just get a 500 Internal Server Error (extremely unhelpful). I cannot turn on errors as it is on a server that multiple people use.
I also tried changing the file_exists line to;
if (file_exists('test.txt'))
in the hopes that would work but still didn't work.
Just to clarify, I'm sending the files from the remote server to my local server.
There is a closing curly brace missing right before the second else keyword.
Please try to use a code editor with proper syntax highlighting and code formatting to spot such mistakes on the fly while you are still editing the PHP file.
The corrected and formatted code:
require('constants.php');
$files = $sftp->nlist('out/');
foreach ($files as $file) {
if (basename((string)$file)) {
if (strpos($file, ".") > 1) { //Checks if file
$filesize = $sftp->size('out/' . $file); //gets filesize
if ($filesize > 1) {
if (file_exists('import/' . $file)) {
echo $file . ' already exists';
} else {
$sftp->get('out/' . $file, 'import/' . $file); //Sends file over
}
} else {
echo $file . ' is empty.</br>';
}
}
}
}
Your code checks the file exist in your local server not in remote server.
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
You need to check in remote server using sftp object like
if($sftp->file_exists('import/'.$file)){
echo $file.' already exists';
}
Edit:
Add clearstatcache() before checking file_exists() function as the results of the function get cached.
Refer: file_exists
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);
}
I'm completely at a loss for explaining why this isn't working. HELP!
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if ($res === 'TRUE') {
$unzip_success= $zip->extractTo('/temp/', "inscriptions.txt")
$zip->close();
}
the target dir "temp" is "0777" permissions
the code obtained from $res is "11" and not "TRUE" as required by the documentation on PHP.net
note: must put the full url for $archive and the first argument of extractTo
if nothing works then check if your server is linux.
if its linux you can run unzip command to unzip your file via php's system/exec function.
i.e
system("unzip archive.zip");
to extract specific file you can check man docs for unzip. many times due to server parameters zip library doesn't work as expected in that cases i switch back to linux commands.
The problem is that you are quoting TRUE, which is a keyword and should be left without single quotes. Plus, you could check if the file exists in the zip archive prior to its extraction with locateName:
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if ($res === true && $zip->locateName('inscriptions.txt') !== false) {
$unzip_success= $zip->extractTo('/tmp/', "inscriptions.txt");
$zip->close();
}
ZipArcive::extractTo is case-sensitive. If file's name to be extracted do not meet zipped one exactly, the method returns false.
I faced the same problem, I have fixed this :)
Use $_SERVER['DOCUMENT_ROOT'] for url.
My code (codeigniter):
$this->load->library('unzip');
$file = $this->input->GET('file');
$this->unzip->extract($_SERVER['DOCUMENT_ROOT'].'/TRAS/application/uploads/' . $file,$_SERVER['DOCUMENT_ROOT'].'/TRAS/application/views/templates/' . $file);
If $res is equal to 11, that means that ZipArchive can't open the specified file.
To test this:
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if($res == ZipArchive::ER_OPEN){
echo "Unable to open $archive\n";
}
Adding document root is what worked for me as well. here is my code
$zip = new ZipArchive;
if ($zip->open($_SERVER['DOCUMENT_ROOT'].'/'.$folder.$file_path) === TRUE) {
$zip->extractTo($_SERVER['DOCUMENT_ROOT'].'/$folder');
$zip->close();
echo 'ok';
}
I meet same problem, but I can open the zip file, it returns true after open.
My issue is I got false after $zip->extractTo().
I finally success after delete files named in CHINESE (NO-ENGILISH) in the zip file.
I had the same problem on Windows 10. The only solution I found was just to try extractTo twice, even though the open() was successful:
$zip = new ZipArchive;
if ($open === true) {
$result = $zip->extractTo($destination);
if ($result === false) {
$result = $zip->extractTo($destination);
}
$zip->close();
}
The fact that the second extractTo() works (with no intervening action) would seem to indicate that there's nothing wrong with the archive or the destination directory.
I wrote this code to create a ZIP file and to save it. But somehow it just doesn't show any error, but it doesn't create a ZIP file either. Here's the code:
$zip = new ZipArchive;
$time = microtime(true);
$res = $zip->open("maps/zips/test_" . $time . ".zip", ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
What am I doing wrong, and how can I fix it?
Probably apache or php has not got permissions to create zip archives in that directory. From one of the comments on ZipArchice::open:
If the directory you are writing or
saving into does not have the correct
permissions set, you won't get any
error messages and it will look like
everything worked fine... except it
won't have changed!
Instead make sure you collect the
return value of ZipArchive::close().
If it is false... it didn't work.
Add an else clause to your if statement and dump $res to see the results:
if($res === TRUE) {
...
} else {
var_dump($res);
}
There are 2 cases when zip doesn't generate the error.
Make sure every file you are adding to the zip is valid. Even if
one file is not available when zip->close is called then the archive
will fail and your zip file won't be created.
If your folder doesn't
have write permissions zip will not report the error. It will finish
but nothing will be created.
I had an exactly same issue, even when with full writing/reading permissions.
Solved by creating the ".zip" file manually before passing it to ZipArchive:
$zip = new ZipArchive;
$time = microtime(true);
$path = "maps/zips/test_" . $time . ".zip"
touch($path); //<--- this line creates the file
$res = $zip->open($path, ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
Check out that each of your file exists before calling $zip->addFile otherwise the zip won't be generated and no error message will be displayed.
if(file_exists($fichier->url))
{
if($zip->addFile($fichier->url,$fichier->nom))
{
$erreur_ouverture = false;
}
else
{
$erreur_ouverture = true;
echo 'Open error : '.$fichier->url;
}
}
else
{
echo 'File '.$fichier->url.' not found';
}
break it into steps.
if ($res === TRUE) {
check if file_exist
check if addFile give any error
}
if($zip->close())
{
$zip_created = true;
echo "FILE ADDED!"
}
Check the phpinfo for zip is enabled or not :)
One of the reasons for zip file is not created is due to missing check if you are adding file and not a directory.
if (!$file->isDir())
I found the solution here.