I can't make ZipArchive create a zip file, but it won't give me any errors except for returning False on $zip->close();
I'm trying to create a zip archive in a directory a couple down from the one in which the operations are taking place.
$file_name = 'example.txt'; // or whatever, I'm including a few
$zip = new ZipArchive();
$path = getcwd() . '/output/run1/';
$zip_name = 'files_run1.zip';
$zip_p_name = $path . $zip_name;
$res = $zip->open($zip_p_name, ZIPARCHIVE::CREATE);
if (!($res ===TRUE)) echo 'failed, code:'.$res;
else
{
if (file_exists($zip_path . '/' . $file_name))
{
$add = $zip->addFile($zip_path . '/' . $file_name);
if (!($add)) echo "didn't work";
}
else echo "File doesn't exist!";
$close = $zip->close();
if ($close) echo 'File Closed';
else echo 'fail!!';
}
That little lot only outputs 'fail!!'. Any ideas what I'm missing?
Related
I am trying to make zip with help of the below code. It works fine in my localhost. But when I transfer it to DirectAdmin server, It returns error code 9 ZipArchive::ER_NOENT : return 'N No such file';
I don't know how to fix it to create zip
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$file = ABSPATH.'test.php';
$zip = new ZipArchive;
$res = $zip->open($dest, ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($file, $file);
$zip->close();
} else {
echo 'failed, code:' . $res;
}
Tested your script on localhost (Windows). I get the error message "failed, code:9".
#see http://php.net/manual/en/ziparchive.open.php and search for "ZipArchive::ER_NOENT".
I think you need to create the zip file.
When i add ZipArchive::CREATE it works (Output "ok"):
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$file = ABSPATH.'test.php';
$zip = new ZipArchive;
$res = $zip->open($dest, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($file, $file);
$zip->close();
} else {
echo 'failed, code:' . $res;
}
-- UPDATE --
The file test.php inside zip_file_name.zip has the full windows path. There is a directory "C:" inside the the zip file on root level (Windows environment). Is this correct?
In case you dont want absolute path you can use relative path:
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$relativeFile = 'test.php';
$absoluteFile = ABSPATH.$relativeFile;
$zip = new ZipArchive;
$res = $zip->open($dest, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($absoluteFile, $relativeFile);
$zip->close();
} else {
echo 'failed, code:' . $res;
}
I have a very simple script that allows user to upload only .zip or .rar files. I'd like to know how do I know if a file is corrupted or empty?
This my script
if(isset($_POST['customerid']) && $_FILES['file']['tmp_name'] && $_POST['requestid']){
//post variables
$customerid = $_POST['customerid'];
$filename = $_FILES['file']['name'];
$requestid = $_POST['requestid'];
//check if the file is .rar or .zip
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$fileMime = $fileInfo->file($_FILES['file']['tmp_name']);
$validMimes = array(
'zip' => 'application/zip',
'rar' => 'application/x-rar',
);
$fileExt = array_search($fileMime, $validMimes, true);
if($fileExt != 'zip' && $fileExt != 'rar'){
echo 'Not a zip or rar.';
}
//check if the file is corrupted or empty
//if all OK insert file name and path to database
$uservalida_stmt = $conn->prepare("INSERT INTO user_project_files (dateCreated,userid,projectFile,serviceRequestId) VALUES (?,?,?,?)");
$uservalida_stmt ->bind_param('siss',$currentdate,$customerid,$filename,$requestid);
$uservalida_stmt ->execute();
$uservalida_stmt ->close();
//move upload and EXTRACT file to directory
move_uploaded_file($_FILES['file']['tmp_name'], '../user/project/' . $_FILES['file']['name']);
}
The PHP manual has examples for zip. http://php.net/manual/en/zip.examples.php
<?php
$za = new ZipArchive();
$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";
echo "numFile:" . $za->numFiles . "\n";
?>
or check the error codes simply on the open function (http://php.net/manual/en/ziparchive.open.php)
You can also do similar with RAR files (http://php.net/manual/en/rararchive.open.php) but will need to install it first (http://php.net/manual/en/rar.installation.php).
I tried a lot of code, But not work.
<?php
$file = $_GET['file'];
if (isset($file))
{
echo "Unzipping " . $file . "<br>";
if(system('unzip '. $file.' -d dirtounzipto ' ))
{echo 'GGWP';}else{echo 'WTF';}
exit;
}?>
How can i unzip in server. with "system" or "shell_exec" code.
$zip_filename = "test.zip";
$zip_extract_path = "/";
try{
$zip_obj = new ZipArchive;
if (file_exists($zip_filename)) {
$zip_stat = $zip_obj->open($zip_filename);
if ($zip_stat === TRUE) {
$res = $zip_obj->extractTo($zip_extract_path);
if ($res === false) {
throw new Exception("Error in extracting file on server.");
}
$zip_obj->close();
} else {
throw new Exception("Error in open file");
}
} else {
throw new Exception("zip file not found for extraction");
}
}catch (Exception $e) {
echo $e->getMessage();
}
Please make good use of PHP's ZipArchive library:
<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Version requirement: PHP >= 5.2.0, PECL zip >= 1.1.0
UPDATE To create the destination path automatically, you can use:
mkdir($path, 0755, true);
which create the folders required automatically.
PHP has built-in extensions for dealing with compressed files. There should be no need to use system calls for this. ZipArchivedocs is one option.
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
//folder name as per zip file name
$foldername = basename($file, ".zip");
mkdir($foldername, 0755, true);
$path = $path . "/" . $foldername;
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $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.
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.