Extract folder contents from file.tar using PHP - php

I am trying to extract the contents of a folder within a tarball using PHP. I am using the following PHP to download and extract the archive:
<?php
function wget($address,$filename) {
file_put_contents($filename,file_get_contents($address));
}
$newdir = 'test';
echo '<br>Downloading latest gzipped WordPress tarball';
wget('http://wordpress.org/latest.tar.gz', 'latest.tar.gz');
echo '<br>about to Extract from gz';
// decompress from gz
$p = new PharData('latest.tar.gz');
$p->decompress(); // creates files.tar
echo '<br>Extracted from gz';
// unarchive from the tar
$phar = new PharData('latest.tar');
echo '<br>Un-TARd';
$phar->extractTo($newdir);
echo '<br>Complete';
?>
My problem is that this script extracts the tarball into /test/wordpress whereas I need it to extract to /test/. I have read through this documentation on the PHP.net Manual and replaced part of my code to meet one of the examples there. The code I had was:
$phar->extractTo($newdir);
And I changed that to:
$phar->extractTo($newdir, 'wordpress');
But that didn't work. The PHP script processed through to the end but the /test/ directory was empty.
The aim of this is to create a one-click WordPress install on our local dev server.

I know the thread is very old and you probably found solution but maybe I'll save someone else time.
Funcion extractTo expects slash at the end of directory name you want to extract.
So $phar->extractTo($newdir, 'wordpress/'); should work.

Related

A way to change the ownership of Apache to order creating txt file

Could you please tell me how to change Apache ownership in Windows if you guys know, since I cannot create txt files using PHP without permission. According to my issue, I need to be able to authorise a file to be made.
What I am trying to do is create a script that records keystrokes in the Firefox extension section. This script will send the data to an Apache PHP file and store it in a text file. I would appreciate your response if you could.
<?php
session_start();
if (!isset($_POST['key'])) {
echo ("Didn't received any new KEY strokes Yet!");
exit(0);
}
//read and write = a+, If the file does not exist, attempt to create it
$file_log = fopen("key.txt","a+");
if (!isset($_SESSION['site']) || $_SESSION['site'] != $_POST['site']) {
$_SESSION['site'] = $_POST['site'];
fwrite($file_log, "| site : ".$_POST['site']." | ");
}
fwrite($file_log,$_POST['key']);
fclose($file_log);
echo("text saved successfully");
It looks like you are not defining a full path for the file.
Depending on where php is running just calling fopen("key.txt","a+") might default to the root directory.
When creating/modifying files you should specify the full path to the file
fopen("/var/www/mydir/example/path/key.txt","a+")

How to get text form copy protected pdf files or having different fonts?

I am using pdfparser for copy text from PDF files but some PDF files are copy protected or have different fonts so that pdfparser not working for that, is it possible to get text from copy protected PDF?
This is my Code :
// Include Composer autoloader if not already done.
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'vendor/autoload.php';
// Parse pdf file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile('tests.pdf');
// Retrieve all pages from the pdf file.
$pages = $pdf->getPages();
// Loop over each page to extract text.
foreach ($pages as $page) {
echo utf8_encode($page->getText());
}
?>
After trying this code I am not getting any error or warning. This code is only showing blank space. I have also try utf-8 encoding but still it is not working?
If the author of the PDF specified the Permissions flags of the document to not permit Copying or Extracting Text and Graphics then you should consider that. Not all PDF software respects such restrictions however.
\Smalot\PdfParser can't extract password protected files.
I've found a far better solution for that (providing your PHP service is running on a Linux server): use the command line tool “pdftotext” (included in the “poppler” package in, for example, Debian or Ubuntu).
It perfectly handles password protected files (it has an option to give password if required).
Used with something like this, inside a PHP script under web server on a Linux server, with a PDF file submitted through a web form:
// $filepath is the full file path properly extracted from the $_FILES variable
// after form submission.
// Expected running under Linux+Apache+PHP; if not, you may have to find your way.
if (! file_exists($filepath)) {
// In case systemd private temporary directory feature is active.
$filepath = '/proc/'.posix_getppid().'/root'.$filepath;
}
$cwdt = 4; // may be better fine tuned for better column alignment
// “sudo” is necessary mostly with systemd private temporary directory
// feature. Needs proper sudoers configuration, of course.
$cmd = "sudo /usr/bin/pdftotext -nopgbrk -fixed {$cwdt} {$filepath} -";
exec($cmd, $output, $res);
print_r($output);
I don't know if it is an answer to the “or having different fonts” requirement, however.

Create .tar.gz file using PHP

The project I am working on requires creating .tar.gz archives and feeding it to an external service. This external service works only with .tar.gz so another type archive is out of question. The server where the code I am working on will execute does not allow access to system calls. So system, exec, backticks etc. are no bueno. Which means I have to rely on pure PHP implementation to create .tar.gz files.
Having done a bit of research, it seems that PharData will be helpful to achieve the result. However I have hit a wall with it and need some guidance.
Consider the following folder layout:
parent folder
- child folder 1
- child folder 2
- file1
- file2
I am using the below code snippet to create the .tar.gz archive which does the trick but there's a minor issue with the end result, it doesn't contain the parent folder, but everything within it.
$pd = new PharData('archive.tar');
$dir = realpath("parent-folder");
$pd->buildFromDirectory($dir);
$pd->compress(Phar::GZ);
unset( $pd );
unlink('archive.tar');
When the archive is created it must contain the exact folder layout mentioned above. Using the above mentioned code snippet, the archive contains everything except the parent folder which is a deal breaker for the external service:
- child folder 1
- child folder 2
- file1
- file2
The description of buildFromDirectory does mention the following so it not containing the parent folder in the archive is understandable:
Construct a tar/zip archive from the files within a directory.
I have also tried using buildFromIterator but the end result with it also the same, i.e the parent folder isn't included in the archive. I was able to get the desired result using addFile but this is painfully slow.
Having done a bit more research I found the following library : https://github.com/alchemy-fr/Zippy . But this requires composer support which isn't available on the server. I'd appreciate if someone could guide me in achieving the end result. I am also open to using some other methods or library so long as its pure PHP implementation and doesn't require any external dependencies. Not sure if it helps but the server where the code will get executed has PHP 5.6
Use the parent of "parent-folder" as the base for Phar::buildFromDirectory() and use its second parameter to limit the results only to "parent-folder", e.g.:
$parent = dirname("parent-folder");
$pd->buildFromDirectory($parent, '#^'.preg_quote("$parent/parent-folder/", "#").'#');
$pd->compress(Phar::GZ);
I ended up having to do this, and as this question is the first result on google for the problem here's the optimal way to do this, without using a regexp (which does not scale well if you want to extract one directory from a directory that contains many others).
function buildFiles($folder, $dir, $retarr = []) {
$i = new DirectoryIterator("$folder/$dir");
foreach ($i as $d) {
if ($d->isDot()) {
continue;
}
if ($d->isDir()) {
$newdir = "$dir/" . basename($d->getPathname());
$retarr = buildFiles($folder, $newdir, $retarr);
} else {
$dest = "$dir/" . $d->getFilename();
$retarr[$dest] = $d->getPathname();
}
}
return $retarr;
}
$out = "/tmp/file.tar";
$sourcedir = "/data/folder";
$subfolder = "folder2";
$p = new PharData($out);
$filemap = buildFiles($sourcedir, $subfolder);
$iterator = new ArrayIterator($filemap);
$p->buildFromIterator($iterator);
$p->compress(\Phar::GZ);
unlink($out); // $out.gz has been created, remove the original .tar
This allows you to pick /data/folder/folder2 from /data/folder, even if /data/folder contains several million OTHER folders. It then creates a tar.gz with the contents all being prepended with the folder name.

copy pdf into another folder in php

I wanto to copy a pdf file to another folder, and it works, but the file that I open in the destination folder is decoded incorrectly and I can not open.
My code:
$fsrc = fopen($srcz,'r');
$fdest = fopen($destz,'w+');
copy($fsrc,$fdest)
Thanks
Try this:
copy($srcz,$destz);
The copy function in PHP needs the source and destination. Consult the php manual: Php copy
I don't know how that code you have works... see the function copy takes the names of the files:
copy($srz,$destz);
If you want to copy the files opened with fopen you use stream_copy_to_stream, like so:
$fsrc = fopen($srcz,'r');
$fdest = fopen($destz,'w+');
stream_copy_to_stream($fsrc, $fdest);
fclose($fsrc);
fclose($fdest);
Do not forget to close the files!
you should use copy without using fopen because fopen create a resource and copy too .
$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");

Download a dynamically generated file using PHP

This might sound really "nooby" but I need to find a way for PHP to download an XLS file to a server folder. This file is not stored in another server, it is dynamically generated with another PHP script.
This is what I got from browsing the web but it's not working:
<?php
$url = "http://localhost/ProyectoAdmin/admin/export_to_excel.php?id=1&searchtype_id=2";
$local_file_path = './xls_tmp/Report.xls';
$xlsFile = file_get_contents($url);
file_put_contents($file_path,$xlsFile);
?>
I'd really appreciate any hint.
You're missing an end quote on your second line.
It should be: $local_file_path = './xls_tmp/Report.xls';

Categories