Unpack/extract zip file with PHP without relying on any extension - php

Is there any way to unpack or extract a zip file with PHP that does not rely on any installed extension? Has anyone written a class or something that can handle it?
Alternatively, is there a solution that uses an extension that is relatively commonly installed on most servers?
I need this to work on as many different servers that I have no control over as possible.
Thanks for any help!

Check this lib it helps to solve same problem
require_once('pclzip.lib.php');
$archive = new PclZip(dirname(__FILE__).'/Archive.zip');
if ($archive->extract(PCLZIP_OPT_PATH, dirname(__FILE__).'/extract') == 0) {
echo "\n error while extract";
} else {
echo "\n extract ok";
}

Well, it looks like most of them require php.ini settings, which you may be able to override in your script:
http://www.w3schools.com/php/php_ref_zip.asp
http://devzone.zend.com/article/2105
and here is how to edit the php.ini file without direct access:
http://www.whenpenguinsattack.com/2006/01/20/how-to-override-phpini/

Related

PHP - create standard zip file with zlib

I have just now discovered that my hosting server does not support the ZIP class for PHP.
However, it has the Zlib installed and supported .
Is there any library / function / hack / class / that will let me handle ZIP files on such a server ?
Basically I want to create zip files. I am afraid my users will be scared of the GZ extension and i would like to serve them ZIP extension (that they will open normally on win systems) ?
(please do not tell me to change hosting - I already know I have to , but it will take time and the thing is quite urgent..)
UPDATE I . thanks to #Mark Baker - i was able to extract a file with the pclzip class and this simple code
<?php
include('pclzip.lib.php');
$archive = new PclZip('wp.zip');
$location = $_SERVER['DOCUMENT_ROOT'];
if ($archive->extract(PCLZIP_OPT_PATH, $location ,
PCLZIP_OPT_REMOVE_PATH, 'install/release') == 0) {
die("Error : ".$archive->errorInfo(true));
}
?>
(I just wanted to post the code here , it was too lng for comment , and I did not wanted to post another answer )
Still did not tested the creation, but if it works the same - then I really want to kiss the developers of that class ! :-)
Zlib doesn't help you create zip files.
As an alternative to your missing ZipArchive, you might take a look at the PCLZip library. This is pure PHP, so no need for additional extensions, and allows you to create zip files without ZipArchive.
I believe that on windows the extension only tells it what application to use to open it.
So you could just save it as something winzip will open, and then just rename it...

Extract a Zip Archive using PHP

what i'm trying to do is to basically extract the contents of Zip archives on my server.Here is some code:
$entry="test.zip";
$zip = new ZipArchive;
if ($zip->open($entry,ZIPARCHIVE::OVERWRITE) === TRUE)
{
$zip->extractTo('unpacked');
$zip->close();
}else
{
echo ‘failed’;
}
the directory "unpacked" is writeable for everyone and all the used methods of the ZipArchive Class return true. However nothing is being extracted. Does anyone happen to have an idea what could cause this behaviour? Any hint will be highly appreciated...Thanks in advance!
If you are using PHP 5.2.0 or later can you check zlib extension first http://www.zlib.net/
You also check PECL extensions, In order to access ZipArchive, you can also try zip_open, zip_read just for checking.
If this code is in-house, and you can safely make the assumption that you won't move this code from Linux to Windows (or vice versa), you also have the option to execute local system commands, which may help solve your problem.
<?php
echo `unzip myarchive.zip`;
echo `tar -xzf myotherarchive.tar.gz`;
?>
When developing internal-use and/or maintenance scripts, I used to opt for straight-up system calls, as it was more in-line with the commands sysadmins were used to using.
In case of failure you should echo out $zip as it contains the error.
Furthermore I'd guess that you may not have the needed permissions for test.zip
If your zip archive is big, sometimes you cannot extract all files during the maximum allowed execution time of your server.
The only solution, if you cannot change the maximum_execution_time in your php.ini, is to use a javascript to extract one file after the other. On the first javascript request you take the number of files in the archive
$nbr_of_files = $zip->numFiles;
And after you extract one file after another using the id number in the zip archive for each file
$zip->extractTo('unpacked', array($zip->getNameIndex($file_nbr)));
Please try removing the ZIPARCHIVE::OVERWRITE flag from the ZipArchive open method. (The flag may not be functioning as expected and may be the root of the issue if you have followed the advice in the other answers.)
I had the same issue too. The solution:
$zip->extractTo(public_path() .'/restoreDb/extracted/');
add the public_path() helper function.

Add AV Scan to File Upload Site

i am not sure whether this is in the right section or not but i am building an file upload site and want to be able to scan the files on upload for viruses etc.. How would i be able to do this?
Any ideas to get me started?
Thanks
The clamav library has a PHP binding called php-clamav. You then can scan files for viruses from within your PHP code:
if ($_FILES['file']['size'] == 0 || !is_file($_FILES['file']['tmp_name']))
{
throw new Exception('Please select a file for upload!');
} else {
cl_setlimits(5, 1000, 200, 0, 10485760);
if ($malware = cl_scanfile($_FILES['file']['tmp_name']))
throw new Exception($malware.'(ClamAV version: '.clam_get_version(),')');
}
...
Another alternative is to install the Mod_Security web application firewall. It can be configured to scan all upload files for viruses using modsec-clamscan.
You could try something like the following using AVG:
Windows:
<?php
exec("avgscanx.exe /SCAN=filename.ext/");
$result = exec("echo %ERRORLEVEL%");
?>
Linux:
<?php
exec("avgscan filename.ext -a -H -c");
$result = exec("echo $?");
?>
Both platforms return the same error codes, allowing you to determine whether a scan was successful or not.
References:
http://www.avg.com/ww-en/faq.num-4443
http://www.avg.com/ww-en/faq.num-4441
http://www.avg.com/ww-en/faq.num-1854
http://www.avg.com/ww-en/faq.num-1759
It depends on your server configuration, but for example on linux, it's easy to install something like clam and access it through the command line. You can use something like php's exec() to run it.
You could also use VirusTotals public API. You can read more about it here. There is some PHP code available here.
This way you get a lot of scanners, and you don't have to run AV locally. On the other hand you'll have to wait a while for the result.

How can I get the path of the PHP binary from PHP?

How can I get the binary path of php from PHP?
I saw it in phpinfo(), but I need another method that gets it in Linux and Windows systems.
You can use:
$_SERVER['_']
Also, the predefined constant PHP_BINDIR gives the directory where the PHP executable is found.
Sample on CodePad and Ideone.
It looks like, for security reasons, $_SERVER values are not exposed.
Linux Only
Use the "which" command to find php.
$phpPath = exec("which php");
Note this does not guarantee the same php executable that your web server may be using, but rather the first instance that was found while looking through the paths.
A method using environment variables, assuming the php executable is in the system path.
function getPHPExecutableFromPath() {
$paths = explode(PATH_SEPARATOR, getenv('PATH'));
foreach ($paths as $path) {
// We need this for XAMPP (Windows)
if (strstr($path, 'php.exe') && isset($_SERVER["WINDIR"]) && file_exists($path) && is_file($path)) {
return $path;
}
else {
$php_executable = $path . DIRECTORY_SEPARATOR . "php" . (isset($_SERVER["WINDIR"]) ? ".exe" : "");
if (file_exists($php_executable) && is_file($php_executable)) {
return $php_executable;
}
}
}
return FALSE; // Not found
}
Maybe the best solution is in the Symfony process component:
PhpExecutableFinder.php and ExecutableFinder.php. In use:
<?php
use Symfony\Component\Process\PhpExecutableFinder;
$phpFinder = new PhpExecutableFinder;
if (!$phpPath = $phpFinder->find()) {
throw new \Exception('The php executable could not be found, add it to your PATH environment variable and try again');
}
return $phpPath;
In Windows, using WAMP, you can use the ini variable - extension_dir - as it is placed in the PHP folder.
Like this:
echo str_replace('ext/', 'php.exe', ini_get('extension_dir'));
Normally, in a simple default PHP installation under Windows, the php.ini file is located and loaded from the same directory of the PHP binary.
To simplify, Windows users:
echo dirname(php_ini_loaded_file()).DIRECTORY_SEPARATOR.'php.exe';
Voilà!
Of course, if you are using multiple .ini files, it may not work if the files are not into the same PHP binary directory. BTW, this may solve to most of cases. Windows developers running PHP from local development environment.
As of PHP 5.4 you can simply use the PHP_BINARY reserved constant.
It's very easy!
var_dump(getenv('PHPBIN'));
But it works only on Windows, so we should use this answer.
How did I get this? I just typed echo echo phpinfo(); and searched the php path there. Just see here:
Then I just getting it here: php getenv and ... you see the result.
For Windows and XAMPP:
$php = getenv('PHPRC') . '/php.exe';
if(is_file($expected)){
return $php;
}

PHP Wamp is not finding a file which exists

I'm having a critical issue where my WAMP installation for PHP 5.3.0 is not finding a file which exists within my computer. Does anyone know anything about this? Possibly a PHP Bug?
Any help would be much appreciated.
Here is the variable which creates the file:
$baseNewsUrl = "C:/reviews/reviews/$platform/$fullname";
And here is the code which grabs the contents:
if(is_file($baseNewsUrl)){
$contents = file_get_contents($baseNewsUrl);
} else {
echo "File not found. " . "\r\n";
continue;
}
Here is the output of $baseNewsUrl: C:/reviews/reviews/GBA/r20107_GBA.htm
And the file does exist.
Check that the entire path leading up to your file is readable by the user PHP is running as (if you are using IIS, this might be something like "Network Service," although I am not particularly experienced with PHP on Windows). Also, check whether the INI directives "open_basedir" or perhaps "safe_mode" are set--these would give PHP self-imposed limits on which files are accessible.
Do a var_dump (not an echo) on your variable.
var_dump($baseNewsUrl);
and look at the actual contents. You may have some invisible garbage characters in there that's preventing Windows if you're doing this in a browser to make sure there's no empty tags (or other browser-render-invisible) characters.
If that doesn't reveal anything, remove the is_file check and try to open the file with file_get_contents (or any file related function) and var_dump it's contents. You'll either open the file, or PHP will spit out an error/warning/notice (either to your browser or to your error log) that should let you know why it can't open the file.
I'm gonna say this, and it very well might not be your problem but it is a recurring one for me. If you use skype on your computer, it has a somewhat known compatibility issue with WAMP. It cause's WAMP to be unstable, not load files properly.. everything.
on windows
$baseNewsUrl = "C:\\reviews\\reviews\\$platform\\$fullname";
It's due to Windows Vista and WAMP.

Categories