Creation of zip folder in php - ftp

I am trying to create a zip folder of my downloaded images.
Here is my code. I am not getting any errors, but the zip is not getting downloaded.The code is getting compiled and I am getting the output till the display part of the current directory, but after that the code seems to go wrong somewhere and I am not able to get any Zip archive.
<?php
$conn_id=ftp_connect("localhost") or die("Could not connect");
ftp_login($conn_id,"kishan","ubuntu"); //login to ftp localhost
echo "The current directory is " . ftp_pwd($conn_id); //display current directory
ftp_chdir($conn_id,'/var/www/test1'); //changing to the directory where my images are downloaded.
echo "<br/><p> Changing to directory" . ftp_pwd($conn_id);
$file_folder=".";
echo "<br/> The content of the directory is <br/>";
print_r(ftp_rawlist($conn_id,".")); // display the contents of the directory
if(extension_loaded('zip')) //check whether extension is loaded
{
$zip=new ZipArchive();
$zip_name="a.zip"; //some name to my zip file
if($zip->open($zip_name,ZIPARCHIVE::CREATE)!==TRUE)
{
$error="Sorry ZIP creation failed at this time";
}
$contents=ftp_nlist($conn_id,".");
foreach($contents as $file) //addition of files to zip one-by-one
{
$zip->addFile($file_folder.$file);
}
$zip->close(); //seal the zip
}
if(file_exists($zip_name)) //Content-dispostion of my zip file
{
header('Content-type:application/zip');
header('Content-Disposition:attachment; filename="'.$zip_name.'"');
readfile($zip_name);
unlink($zip_name);
}
?>

I just found that there is something wrong with the data that is passed to the for loop.
$contents=ftp_nlist($conn_id,".");
foreach($contents as $file) //addition of files to zip one-by-one
{
$zip->addFile($file_folder.$file);
}
I am not sure exactly where the thing is going wrong but here is the update. What I did was write markup using html and then passing the files to this php script via a POST method, as
foreach($post['files'] as $file){
$zip->addFile($file_folder.$file);} // Adding files into zip
This code is absolutely working fine, but now I need to figure out why post method is working and compressing my files whereas my normal for looping over files is not!!

Related

How to read a .docx file via PHP Word sample code in Codeigniter

Am trying to read a .docx file which is inside my project folder via PHP Word library. I have included autoloader like this :
include_once 'vendor/autoload.php'; in my controller.
CODE FOR FUNCTION IN CONTROLLER:
function test_phpword()
{
$a=base_url();
$path=$a."".'123.docx';
$source =$path;
echo date('H:i:s'), " Reading contents from `{$source}`";
$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
echo write($phpWord, basename(__FILE__, '.php'), $writers);
}
BUT GETTING ERROR LIKE BELOW:
06:18:42 Reading contents from http://localhost/myproject/123.docx
Fatal error: Uncaught Exception: Cannot find archive file. in /opt/lampp/htdocs/myproject/vendor/phpoffice/common/src/Common/XMLReader.php:51
Try this
Change
$path=$a."".'123.docx';
to
$path='123.docx';
And put 123.docx beside your php script file. make sure the two files are in the same place. Run your php script again.
If this helps and works fine you can check the file path and make proper change to your php program.
While loading the path, you have to give relative path to the doc file as shown below,
$random_name = 123.docx;
$contents = \PhpOffice\PhpWord\IOFactory::load('../uploads/'.$random_name);
I don't know whats your $base_url, but it will not work if it is absolute path like http://path/to/doc/file.
I have worked on it and tested. Hope it helps.

How to copy more than 5k files with FTP client from linux server

i need to backup a site's FTP. The site is hosted on a linux server. The problem is that there is a folder with more than 5k files. Linux can't show me more than 4998 files, so i cant copy these files 'cause the server don't give me more than 4998.
I can't delete these files to see the others 'cause the site is actually online. I can't move these file in another directory for the same reason.
What can i do? i'm trying using a shell...but i don't know...i'm not sure using this method.
I got solution for my own answer
<?php
$rootPath = realpath('wp-content/uploads/2014/07');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('dio.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
You can do this through the command line, this guide shows you how. It seems mget (the ftp command) isn't recommended for recursive calls (subfolders and their content), so wget can also be used, se this.
I also like to zip such folders with many files into one, for easy oversight when up-and-downloading. Use
zip -r myfiles.zip myfiles
Here's a guide for that too.

Laravel downloads a file with unknown type

I am using Laravel 4. I allow users to upload a file, which is programmatically renamed with some number and stored. I also allow them to download the files, though I am supposed to rename their file from some funny number to their name, and download it.
My problem is, how can I change filename just before its downloaded?
My code:
return Response::download($pathToFile, $name);
When I do that, the file is downloaded with unknown format.
The second $name parameter, needs to include the full filename (including the file extension). The download method does not automatically detect the extension from the file path and append it to the name, so that needs to be done manually. Something like this will work:
return Response::download(
$pathToFile,
$name . '.' . pathinfo($pathToFile, PATHINFO_EXTENSION)
);

CakePHP - need URL to route to the tmp directory?

I am trying to create thumbnail pics using GD lib in Cake PHP.
I can write the resized thumbnail to the tmp directory, and create the sensible URL to show the image from the tmp directory:
//set up empty GD resource
$tmp = imagecreatetruecolor(200*$iw/$ih, 200);
//create thumbnail image in the empty GD resource
imagecopyresampled($tmp, $src, 0, 0, 0, 0,200*$iw/$ih, 200, $iw, $ih);
//build full path to thumbnail in the cakephp tmp directory
$thumbfile = APP.'tmp/thumb.jpg';
//build URL path to the same thumbnail
$thumblink = $this->webroot.'tmp/thumb.jpg';
//write jpeg to the tmp directory
$return=imagejpeg($tmp,$thumbfile);
//write out the image to client browser
echo "<img=\"$thumblink\" alt=\"thumb\" height=\"200\" width=\"200*$iw/$ih\">";
The thumbnail gets created and written to the tmp directory, but when I try to access the URL I get the following error message:
Error: TmpController could not be found.
Error: Create the class TmpController below in file: app/Controller/TmpController.php
Obviously I have a routing error - Cake tries to call the tmp controller, in stead of looking in the tmp direcectory. How can I fix this, or is there an alternative way to serve temporary thumbnails using GD lib?
I am planning to create unique thumbnails per session or user, but I need to get this working first.
Routing in Config/routes.php:
Router::connect('/', array('controller' => 'MsCake', 'action' => 'index'));
Router::connect('/pages/*', array('controller' => 'pages'));
CakePlugin::routes();
I looked at ThumbnailHelper, but that doesn't use GD Lib. I also need to be able to access files stored on non-apache accessible directories from outside, but I can't even access any temporary symbolic links to get to them. eg.
create a temporary symbolic link in the tmp directory, pointing to the file in question.
create a HTML link, pointing to the symbolic link using $this->webroot.'tmp/link-to-myfile', as above
...and I get the same error as above - Error: TmpController could not be found.
Don't do that
If you do anything to make files in the tmp dir web-accessible - you're severely lowering your site's security. Things in the tmp directory are never supposed to be web accessible.
Put your images in the webroot
A better idea is to put your temporary images in the webroot directory - which is the only directory that is ordinarily web accessible. For example:
$filename = md5($userId);
$thumbfile = APP.'webroot/img/cache/' . $filename . '.jpg';
...
$url = '/img/cache/' . $filename . '.jpg';
Or route to a controller action
Alternatively, route to a controller action to handle the request using the media view class. Note however though, that serving images with php is not free - there can be a noticable delay while your request is processed - where'as pointing at a static file does not have this cost/risk since it's just the webserver taking care of serving the content.
Since it's temporary, what you could do is to display the image as a data url instead of to the tmp directory, like so (replace from after imagecopyresampled() call):
ob_start();
imagepng($tmp);
$contents = ob_get_contents();
ob_end_clean();
imagedestroy($tmp);
//write out the image to client browser
echo "<img src='data:image/png;base64,".base64_encode($contents)."' alt='thumb' height='200' width='".(200*$iw/$ih)."'>";
This uses a bit more bandwidth since the image is base64 encoded rather than sent as binary.

How do I get the full local path of a file uploaded with $_FILES

I am uploaded a file through the file input. If I print_r($_FILES), I can get several pieces of info, but it doesn't give me the full LOCAL path of the file (the path on my computer, not the server). How do I get this?
I need this to use the FTP library in CodeIgniter. Documentation is here on how to use it to upload a file.
As you can see, it requires the full local path, although I'm not sure why.
As file upload path is a variable which changes from server to server, I would suggest you to use move_uploaded_file() function:
$target = "uploads/myfile.something";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target)) {
// do something
}
that way it will always work no matter what the path is even if it changes. The target can be anything you wish, it's relative to the current folder where script is being executed.
I solved this.
public function upload($file, $folder) {
$this->CI->ftp->upload($_FILES['file']['tmp_name'], '/public_html/rest/of/path/' . $_FILES['file']['name'], 'ascii', 0775);
}
The file is being uploaded, so you can access it with $FILES['file']['tmp_name']. This is from within a class, so that's why I'm using $this->CI. Otherwise, I would just use $this.

Resources