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.
Related
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...
What I would like to script: a PHP script to find a certain string in loads of files
Is it possible to read contents of thousands of text files from another ftp server without actually downloading those files (ftp_get) ?
If not, would downloading them ONCE -> if already exists = skip / filesize differs = redownload -> search certain string -> ...
be the easiest option?
If URL fopen wrappers are enabled, then file_get_contents can do the trick and you do not need to save the file on your server.
<?php
$find = 'mytext'; //text to find
$files = array('http://example.com/file1.txt', 'http://example.com/file2.txt'); //source files
foreach($files as $file)
{
$data = file_get_contents($file);
if(strpos($data, $find) !== FALSE)
echo "found in $file".PHP_EOL;
}
?>
[EDIT]: If Files are accessible only by FTP:
In that case, you have to use like this:
$files = array('ftp://user:pass#domain.com/path/to/file', 'ftp://user:pass#domain.com/path/to/file2');
If you are going to store the files after you download them, then you may be better served to just download or update all of the files, then search through them for the string.
The best approach depends on how you will use it.
If you are going to be deleting the files after you have searched them, then you may want to also keep track of which ones you searched, and their file date information, so that later, when you go to search again, you won't waste time searching files that haven't changed since the last time you checked them.
When you are dealing with so many files, try to cache any information that will help your program to be more efficient next time it runs.
PHP's built-in file reading functions, such as fopen()/fread()/fclose() and file_get_contents() do support FTP URLs, like this:
<?php
$data = file_get_contents('ftp://user:password#ftp.example.com/dir/file');
// The file's contents are stored in the $data variable
If you would need to get a list of the files in the directory, you might want to check out opendir(), readdir() and closedir(), which I'm pretty sure supports FTP URLs.
An example:
<?php
$dir = opendir('ftp://user:password#ftp.example.com/dir/');
if(!$dir)
die;
while(($file = readdir($dir)) !== false)
echo htmlspecialchars($file).'<br />';
closedir($dir);
If you can connect via SSH to that server, and if you can install new PECL (and PEAR) modules, then you might consider using PHP SSH2. Here's a good tutorial on how to install and use it. This is a better alternative to FTP. But if it is not possible, your only solution is file_get_content('ftp://domain/path/to/remote/file');.
** UPDATE **
Here is a PHP-only implementation of an SSH client : SSH in PHP.
With FTP you'll always have to download to check.
I do not know what kind of bandwidth you're having and how big the files are, but this might be an interesting use-case to run this from the cloud like Amazon EC2, or google-apps (if you can download the files in the timelimit).
In the EC2 case you then spin up the server for an hour to check for updates in the files and shut it down again afterwards. This will cost a couple of bucks per month and avoid you from potentially upgrading your line or hosting contract.
If this is a regular task then it might be worth using a simple queue system so you can run multiple processes at once (will hugely increase speed) This would involve two steps:
Get a list of all files on the remote server
Put the list into a queue (you can use memcached for a basic message queuing system)
Use a seperate script to get the next item from the queue.
The procesing script would contain simple functionality (in do while loop)
ftp_connect
do
item = next item from queue
$contents = file_get_contents;
preg_match(.., $contents);
while (true);
ftp close
You could then in theory fork off multiple processes through the command line without needing to worry about race conditions.
This method is probabaly best suited to crons/batch processing, however it might work in this situation too.
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.
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/
I am writing a simple SFTP client in PHP because we have the need to programatically retrieve files via n remote servers. I am using the PECL SSH2 extension.
I have run up against a road block, though. The documentation on php.net suggests that you can do this:
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
However, I have an ls method that attempts to something similar
public function ls($dir)
{
$rd = "ssh2.sftp://{$this->sftp}/$dir";
$handle = opendir($rd);
if (!is_resource($handle)) {
throw new SFTPException("Could not open directory.");
}
while (false !== ($file = readdir($handle))) {
if (substr($file, 0, 1) != '.'){
print $file . "\n";
}
}
closedir($handle);
}
I get the following error:
PHP Warning: opendir(): Unable to open ssh2.sftp://Resource id #5/outgoing on remote host
This makes perfect sense because that's what happens when you cast a resource to string. Is the documentation wrong? I tried replacing the resource with host, username, and host and that didn't work either. I know the path is correct because I can run SFTP from the command line and it works fine.
Has anyone else tried to use the SSH2 extenstion with SFTP? Am I missing something obvious here?
UPDATE:
I setup sftp on another machine in-house and it works just fine. So, there must be something about the server I am trying to connect to that isn't working.
When connecting to a SFTP server and you need to connect to the root folder (for instance for reading the content of the folder) you would still get the error when using just "/" as the path.
The solution that I found was to use the path "/./", that's a valid path that references to the root folder. This is useful when the user you are logging with has access only to its own root folder and no full path is available.
So the request to the server when trying to read the contents of the root folder should be something like this:
$rd = "ssh2.sftp://{$this->sftp}/./";
For php versions > 5.6.27 use intval()
$sftpConnection = ssh2_connect($host);
$sftp = ssh2_sftp($sftpConnection);
$fp = fopen("ssh2.sftp://" . intval($sftp) . $remoteFile, "r");
https://bugs.php.net/bug.php?id=73597
I'm having a similar issue. I assume you are doing something similar to this:
$dir = "ssh2.sftp://{$sftp}{$remote_dir}";
$handle = opendir($dir);
When $remote_dir is the full path from root then open_dir works. If $remote_dir is just '/' or '', then I get the 'unable to open' error as you did.
In my case, it seems ssh connects at the root folder instead of the 'home' directory as ftp does. You mentioned that it worked on a different server, so I wonder if it is just a config issue.
the most easiest way to get SFTP working within PHP (even on windows) without installing any extension etc is PHPSECLIB: http://phpseclib.sourceforge.net/ . The SSH stuff is completely implemented in a PHP class.
You use is like this:
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
echo $sftp->pwd();
?>
The documentation on that page contains an error. Take a look at the example here instead: http://php.net/ssh2_sftp - what you actually need to do is to open a special SFTP resource using ssh2_sftp() prior to using it with fopen(). And yes, it looks just like that, e.g. "Resource #24" when converted to string... a bit weird but apparently it works.
Another caveat is that SFTP starts in the root directory rather than the home directory of the remote user, so your remote path in the URI should always be an absolute one.
I just had the same issue, but I could figure out the problem.
On my case, when connecting to the server, I was going to the root of the account, and due to server configs I wasn't able to write there.
I have connected to the account using a fireFTP, and so I could see where the root of the account was...it was the root of the server.
I had to include the whole path until the folder where I am allowed to write, and so I could solve the issue.
So, my advice is to get the path using a graphic interface (I have used fireFTP), and add the whole path to your code.
$pathFromAccountRootFolderToMyDestinationFolder = '/Account/Root/Folder/To/My/Folder';
$stream = fopen("ssh2.sftp://".$sftp."/".$pathFromAccountRootFolderToMyDestinationFolder."/myFile.ext", 'r');
Hope this will help you and other people with the same issue!
Cheers!
I recently tried to get SFTP on PHP working and found that phpseclib was a lot easier to use:
http://phpseclib.sourceforge.net/
If you have the luxury of not being on a shared host and can install whatever extensions you want to maybe the PECL extension would be better but not all of us are so lucky. Plus, phpseclib's API looks a bit more intuitive, being OOP and all.
My issue was, that I was connecting in function and returning string URL with resource inside. Unfortunatelly resource is than created in function context and garbage collector is disconnecting resource on function end. Solution: return resource by reference and unset it manually in more complex context.
Solved my issue by enabling sftp support on the (Powershell) server
This is a bug in the ssh2 package that I found years ago and posted a patch to php.net. It fixes this issue but requires a rebuild of the ssh2 pecl package. You can read more here: https://bugs.php.net/bug.php?id=69981. I included a patch there to the ssh2_fopen_wrappers.c file in the package to fix the issue. Here is a comment I included:
Here is a line of code from ssh2_fopen_wrappers.c that causes this bug: (comment included)
/*
Find resource->path in the path string, then copy the entire string from the original path.
This includes ?query#fragment in the path string
*/
resource->path = estrdup(strstr(path, resource->path));
This line of code -- and therefore this bug -- was introduced as a fix for bug #59794. That line of code is attempting to get a string containing the part, query and fragment from the path variable.
Consider this value for the path variable:
ssh2.sftp://Resource id #5/topdir?a=something#heading1
When resource->path is "/topdir", the result is that "/topdir?a=something#heading1" gets assigned to resource->path just like the comment says.
Now consider the case when resource->path is "/". After the line of code is executed, resource->path becomes "//Resource id#5/topdir#heading1". This is clearly not what you want. Here's a line of code that does:
resource->path = estrdup( strstr( strstr( path, "//" ) + 2, "/" ) );
You may also need to apply the patch for bug # 73597 which removes "Resource id #" from the path string before calling php_url_parse().