I want to transfer site from shared hosting server to dedicated server.current server has folder,which includes approx. 16000 images...we can not use FTP to download these much images.and i do not have SSH rights? how can i download images from this shared hosting server.
we can not use FTP to download these much images
Nonsense. FTP (the protocol) is perfectly capable of downloading 16000 files. If your FTP program is causing you trouble, simply pick a better FTP program. If you can handle commandline applications, wget is nice, since it supports recursion and continuation.
Unless they are located within a directory that is within the web root of a web application server you are out of luck.
Zip them all, adapted from http://davidwalsh.name/create-zip-php
<?php
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
//glob images folder into an array
foreach (glob("*.jpg") as $filename) {
$files_to_zip[]='images/'.$filename;
}
//create the zip
$result = create_zip($files_to_zip,'my-images.zip');
if($result==true){echo'Download Images';
}else{
echo'Could not create zip';}
?>
Related
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
}
}
I'm a PHP novice and so looking for some advice on a PHP function i have created to use within a Wordpress installation.
As you can see from the code below, it runs when one of the admin's press 'Publish' on a pending post.
It takes a Zip file that has been uploaded by a user via Gravity Forms, then unzips ONLY .mp3 extensions. Re-zips and moves all the files to a new folder in our Amazon S3 directory.
The code is pieced together from my limited knowledge and some help along the way with questions on here.
So, here's what i ended up with:
add_action('pending_to_publish', 'unzip_to_s3');
function unzip_to_s3() {
global $post;
global $wpdb;
// Only run function if post is portfolio post type
if ('portfolio' == $post->post_type) {
// Set temp path
$temp_path = '../wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/tmp/';
// Get filename from Zip file
$file = get_post_meta($post->ID, 'file_url', true);
$zip_file = basename($file);
// Create full Zip file path
$zip_file_path = $temp_path.$zip_file;
// Generate unique name for temp sub_folder for unzipped files
$temp_unzip_folder = uniqid('temp_TMS_', true);
// Create full temp sub_folder path
$temp_unzip_path = $temp_path.$temp_unzip_folder;
// Make the new temp sub_folder for unzipped files
if (!mkdir($temp_unzip_path, 0755, true)) {
die('Error: Could not create path: '.$temp_unzip_path);
}
// Unzip files to temp unzip folder, ignoring anything that is not a .mp3 extension
$zip = new ZipArchive();
$filename = $zip_file_path;
if ($zip->open($filename)!==TRUE) {
exit("cannot open <$filename>\n");
}
for ($i=0; $i<$zip->numFiles;$i++) {
$info = $zip->statIndex($i);
$file = pathinfo($info['name']);
if(strtolower($file['extension']) == "mp3") {
file_put_contents($temp_unzip_path.'/'.basename($info['name']), $zip->getFromIndex($i));
} else {
$zip->deleteIndex($i);
}
}
$zip->close();
// Re-zip the unzipped mp3's and store new zip file in temp folder created earlier
$temp_unzip_path = $temp_unzip_path.'/';
$zip = new ZipArchive();
$dirArray = array();
$new_zip_file = $temp_unzip_path.$zip_file;
$new = $zip->open($new_zip_file, ZIPARCHIVE::CREATE);
if ($new === true) {
$handle = opendir($temp_unzip_path);
while (false !== ($entry = readdir($handle))) {
if(!in_array($entry,array('.','..')))
{
$dirArray[] = $entry;
$zip->addFile($temp_unzip_path.$entry,$entry);
}
}
closedir($handle);
} else {
echo 'Failed to create Zip';
}
$zip->close();
// Set Media bucket dir
$bucket_path = '../wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/mixtape2/';
// Generate unique name for sub_bucket
$sub_bucket = uniqid('TMS_', true);
// Create full sub_bucket path
$sub_bucket_path = $bucket_path.$sub_bucket;
// Make the new sub_bucket
if (!mkdir($sub_bucket_path, 0755, true)) {
die('Error: Could not create path: '.$sub_bucket_path);
}
// Move mp3's to new sub_bucket
// Get array of all source files
$files = scandir($temp_unzip_path);
// Identify directories
$source = $temp_unzip_path;
$destination = $sub_bucket_path.'/';
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// if move files is successful delete the original temp folder
if (rename($source.$file, $destination.$file)) {
rmdir($temp_unzip_path);
}
}
// Delete original Zip file
unlink($temp_path.$zip_file);
// Update Custom field for new Zip file location
update_post_meta($post->ID, 'file_url', 'http://themixtapesite.com/wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/mixtape2/'.$sub_bucket.'/'.$zip_file);
}
}
Whilst this function does work, we're dealing with large files and so it does take a while to process...
What is happening is when the admin presses publish it triggers this function but the page just sits there until it's finished this function and then will continue. This function can take upto around 5 minutes to run.
I'm looking to optimise this function (in terms of code) but also see if there's a way i can run this in the background so that the admin can carry on with other things and not have to sit there waiting around.
Any help appreciated.
You may want to try to WP cron and schedule the task at that point so that it runs in the background. Here is some resources for that. the basic concept would go something like this.
if ( ! wp_next_scheduled( 'pending_to_publish' ) ) {
wp_schedule_single_event($timestamp,'pending_to_publish');
}
add_action('pending_to_publish', 'unzip_to_s3');
http://wpengineer.com/1908/use-wordpress-cron/
http://codex.wordpress.org/Category%3aWP-Cron_Functions
https://wordpress.stackexchange.com/questions/42694/run-a-cron-job-or-similar-in-the-background-of-wp-after-post-update-create
When I trying to open my zip file which is generated by PHP Zip Archive, there is an alert showing
"Windows cannot open the folder. The Compressed (zipped) Folder
'filename' is invalid." error opening in Windows Explorer.
But I can open the file through 7-zip. In some reason, I have to ensure the zip file can open by Windows Explorer. Is there any problem when I generated the zip file? Please help!
function create_a_zip($files = array(),$dest = '',$root_folder,$overwrite = false) {
if(file_exists($dest) && !$overwrite) {
return false;
}
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($dest,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
foreach($valid_files as $valid_file) {
if(is_dir($valid_file) === true){
foreach(glob($valid_file . '/*') as $file){
$zip->addFile($file, $root_folder . $file);
}
}else if (is_file($valid_file) === true){
$zip->addFile($valid_file, $root_folder . $valid_file);
}
}
$zip->close();
return file_exists($dest);
}
else
{
return false;
}
}
For me, the solution was to use ob_end_clean() before outputting zip file contents (as noted by #Ywis in the comments)...
ob_end_clean();
readfile($zipfilename); // outputs zip file's content
... even if you don't output any characters before that.
I think the problem originates from:
$zip->addFile($file,$file);
Unless you have your php script in the same directory as the files you want to add to zip, you will need to include the file path. The 2nd parameter in addFile is the name of the file inside the zip, so if your $file var includes the path, that’s where the issue probably coming from. Try to change the code to :
$filenameonly = preg_replace("/(.*)\/?([^\/]+)/","$2",$file);
$zip->addFile($file,$filenameonly );
which will strip out the file path (if any) and leave you only the file name for the 2nd variable in addFile.
If this will solve your problem you will know for sure that the problem was in your filenames and can pinpoint it easily.
Just send as parameter to absolute path for example $abspath. Then use it in
$filenameonly = str_replace($abspath,"",$file);
$zip->addFile($file, $filenameonly);
It works 100% even in Window 8 and even your files you zip are in folders.
Instead of using str_replace string function, you can use built-in file-system functions.
$zip->addFile(realpath($file), pathinfo($file, PATHINFO_BASENAME));
Windows zip does not recognize paths begining with "/"
Just remove the first "/" in the filepath.
Like this:
if ( substr($root_folder,0,1) == '/' ) {
$root_folder = substr($root_folder,1);
}
$zip->addFile($file, $root_folder . $file);
I have PHP page which lists some songs based on a criteria such as album year or something. I just placed a checkbox near to every song. When a visitor selects some check box and press submit button the form sends each value to a php file. In the PHP file the values are stored in an array.
$files_to_zip=array();
for($i=0;$i<count($_POST['song'];i++)
$files_to_zip[]=$_POST['song'][$i];
//'song' is the name of the checkbox in the HTML form
The problem is the PHP file does not create the zip file with the code i wrote.
function create_zip($files = array(),$destination = '',$overwrite = true) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
$files_to_zip = array();
foreach($_POST['song'] as $fileabc)
{
$files_to_zip[]=$fileabc;
}
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');
if($result==true)echo "Success"; else echo "failed";
This is the entire code I use in the PHP.
If I set the value for $files_to_zip dynamically such as,
$files_to_zip=array('link1','link2','link3'..)
it works properly.
What is the bug in my code?
I'm using Codeigniter to create a web site, and I tried to create a function to upload the entire directory via FTP to a remote host, but nothing is working
I tried 2 functions I found, but also not working, only few files uploaded, and some files size is 0 bytes
Functions Used :
// 1St Function
public function ftp_copy($src_dir, $dst_dir) {
$d = dir($src_dir);
while($file = $d->read()) {
if ($file != "." && $file != "..") {
if (is_dir($src_dir."/".$file)) {
if (!#ftp_chdir($this->conn_id, $dst_dir."/".$file)) {
ftp_mkdir($this->conn_id, $dst_dir."/".$file);
}
ftp_copy($src_dir."/".$file, $dst_dir."/".$file);
}
else {
$upload = ftp_put($this->conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);
}
}
}
$d->close();
}
// 2nd Solution from Stackoverflow question
foreach (glob("/directory/to/upload/*.*") as $filename)
ftp_put($ftp_stream, basename($filename) , $filename, FTP_BINARY);
Any solution ??
If you are using codeigniter you can use $this->ftp->mirror() from their FTP Library.
http://codeigniter.com/user_guide/libraries/ftp.html
$this->load->library('ftp');
$config['hostname'] = 'ftp.example.com';
$config['username'] = 'your-username';
$config['password'] = 'your-password';
$config['debug'] = TRUE;
$this->ftp->connect($config);
$this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/');
$this->ftp->close();