PHP Tar Extract w/ Variable - php

Understanding that the following question is not best practices by any means. The tool i am building is for personal use and will not be accessible to the internet in general. With that being said here is the idea or outline of what i am trying to accomplish.
PHP:
define("UPLOAD_DIR", "/var/www/html/uploads/");
if (!empty($_FILES["SANUpload"])) {
$myFile = $_FILES["SANUpload"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
}
The goal is once it gets uploaded I need to sort the files and put them in the correct spots. The upload will ALWAYS be a TAR file because the scripts that i built for it the ONLY output is a tar file.
My goal is to extract the tar file in uploads directory and then run move commands to move the files where they need to be. Then do a clean up and delete any files in the UPLOADS dir.
I found this example on here :
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
This is another component i am looking at as well:
try {
$phar = new PharData('myphar.tar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
The problem I am having with PharData is that it doesn't like the $path or $name variables. The same can be said for the example above PharData. Since the upload script could have different names I need to have the ability to unzip the file as a variable or to use a variable in the php script.
Technically - the script I have would keep the tar name the same however I could see a use case where someone might change that. So want to make sure that I have the option to address that.
So question is how do i extract a tar file - utilizing a variable name rather than have it spelled out and the actual name of the file all in PHP?

Figured out the issue - i needed to utilize the UPLOAD_DIR . $name in the pharData.
try {
$phar = new PharData(UPLOAD_DIR . $name);
$phar->extractTo(UPLOAD_DIR); // extract all files
} catch (Exception $e) {
// handle errors
}

Related

receiving binary file sent through CURL

What I'm trying to do is save the binary file sent through CURL from another server.
The php uploader I have is:
<?php
define("UPLOAD_DIR", "/tmp/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
So i have this on my site as such:
example.com/uploader.php
On server number 2, I run the command:
curl --request POST --data-binary "#binary.jpg" http://example.com/uploader.php
and then I check my /tmp/ folder for the file named binary.jpg but it is not there, what is the issue here ?
Thanks.
It may at location where you run curl command. For example if you run at /home/student then binary. Jpg is at the location /home/student/binary. Jpg
After running curl command, are you getting successful transfer message?
In the code, if (!empty($_FILES["myFile"])) { , you are specifically checking field named myFile of array $_FILES and then doing stuff. While the curl command does not suggest that the binary file is being sent with name myFile. You can sepcify the name of the POST fields in you curl command and issue will be resolved hopefully. (Also try printing the whole $_POST and $_FILES array in code for debugging purposes)

Use copy() in a foreach loop to copy multiple files php

I'm trying to copy multiple files from one domain on a web server to another using copy() and looping through a list of files, but it's only copying the last file on the list.
Here is the contents of files-list.txt:
/templates/template.php
/admin/admin.css
/admin/codeSnippets.php
/admin/editPage.php
/admin/index.php
/admin/functions.php
/admin/style.php
/admin/editPost.php
/admin/createPage.php
/admin/createPost.php
/admin/configuration.php
This script runs on the website that I'm trying to copy the files to. Here's the script:
$filesList = file_get_contents("http://copyfromhere.com/copythesefiles/files-list.txt");
$filesArray = explode("\n", $filesList);
foreach($filesArray as $file) {
$filename = trim('http://copyfromhere.com/copythesefiles' . $file);
$dest = "destFolder" . $file;
if(!#copy($filename, $dest))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "$filename copied to $dest from remote!<br/>";
}
}
I get the affirmative message for each and every file individually just as I should, but when I check the directory, only the last file from files-list.txt is there. I've tried changing the order, so I know the problem lies with the script, not any individual file.
The output from the echo statements looks something like this:
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPage.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPost.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/index.php from remote!
Etc
I've modified your code slightly, and tested it on my local dev server. The following seems to work:
$fileURL = 'http://copyfromhere.com/copythesefiles';
$filesArray = file("$fileURL/files-list.txt", FILE_IGNORE_NEW_LINES);
foreach ($filesArray as $file) {
$fileName = "$fileURL/$file";
$dest = str_replace($fileURL, 'destFolder', $fileName);
if (!copy($fileName, $dest)) {
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}
else {
echo "$fileName copied to $dest from remote!<br/>";
}
}
This uses the same fix that Mark B pointed out, but also consolidated the code a little.
Unless the data you're fetching from that remote site has leading/ in the path/filename, you're not generating proper paths:
$file = 'foo.txt'; // example only
$dest = "destFolder" . $file;
produces destFolderfoo.txt, and you end up littering your script's working directory with a bunch of wonky filenames. Perhaps you wanted
$dest = 'destFolder/' . $file;
^----note this
instead.

Can PHP decompress a taz file? (.tar.Z)

I have tried to use Zlib to decompress the file, but it just said "Data error" and gave me an empty file.
This is the code I tried:
// Open a new temp file to write new file to
$tempFile = fopen("tempFile", "w");
// Make sure tempFile is empty
ftruncate($tempFile, 0);
// Write new decompressed file
fwrite($tempFile, zlib_decode(file_get_contents($path))); // $path = absolute path to data.tar.Z
// close temp file
fclose($tempFile);
I have also tried to decompress it in parts, going from .tar.Z to .tar to just a file. I tried using lzw functions to take off the .Z, but I was unable to make it work. Is there a way to do this?
EDIT:
Here is some more code I have tried. Just to make sure the file_get_contents was working. I still get a "data error".
$tempFile = fopen("tempFile.tar", "w");
// Make sure tempFile is empty
ftruncate($tempFile, 0);
// Write new decompressed file
$contents = file_get_contents($path);
if ($contents) {
fwrite($tempFile, gzuncompress($contents));
}
// close temp file
fclose($tempFile);
EDIT2: I think the reason why LZW was not working is because the contents of the .tar.Z file looks like this:
��3dЀ��0p���a�
H�H��ŋ3j��#�6l�
The LZW functions I have tried both use ASCII characters in their dictionaries. What kind of characters are these?
So you want to decompress a taz file natively with PHP? Give my new extension a try!
lzw_decompress_file('3240_05_1948-1998.tar.Z', '3240_05_1948-1998.tar');
$archive = new PharData('/tmp/3240_05_1948-1998.tar');
mkdir('unpacked');
$archive->extractTo('unpacked');
Also note, the reason the zlib functions aren't working is because you need LZW compression, not gzip compression.
according to this url https://kb.iu.edu/d/acsy you can try
<?php
$file = '/tmp/archive.z';
shell_exec("uncompress $file");
if you don't have Unix like OS check https://kb.iu.edu/d/abck for appropriate program.
The file is compressed with LZW compression, and I tried a few but there seems to be no reliable method for decompressing these in PHP. Cosmin's answer contains the correct first step but after using your system's uncompress utility to decompress the file, you still have to extract the TAR file. This can be done with PHP's built-in tools for handling its custom PHAR files.
// the file we're getting
$url = "ftp://ftp.ncdc.noaa.gov/pub/data/hourly_precip-3240/05/3240_05_2011-2011.tar.Z";
// where to save it
$output_dir = ".";
// get a temporary file name
$tempfile = sys_get_temp_dir() . basename($url);
// get the file
$compressed_data = file_get_contents($url);
if (empty($compressed_data)) {
echo "error getting $url";
exit;
}
// save it to a local file
$result = file_put_contents($tempfile, $compressed_data);
if (!$result) {
echo "error saving data to $tempfile";
exit;
}
// run the system uncompress utility
exec("/usr/bin/env uncompress $tempfile", $foo, $return);
if ($return == 0) {
// uncompress strips the .Z off the filename
$tempfile = preg_replace("/.Z$/", "", $tempfile);
// remove .tar from the filename for use as a directory
$tempdir = preg_replace("/.tar$/", "", basename($tempfile));
try {
// extract the tar file
$tarchive = new PharData($tempfile);
$tarchive->extractTo("$output_dir/$tempdir");
// loop through the files
$dir = new DirectoryIterator($tempdir);
foreach ($dir as $file) {
if (!$file->isDot()) {
echo $file->getFileName() . "\n";
}
}
} catch (Exception $e) {
echo "Caught exception untarring: " . $e->getMessage();
exit;
}
} else {
echo "uncompress returned error code $return";
exit;
}
Please try this.
<?php
try {
$phar = new PharData('myphar.tar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>
Source : http://php.net/manual/en/phardata.extractto.php
I haven't tested it but i hope it will work for you.

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

Can't Use unlink function with path defined by variable

I can't read the path by use variable
$absPath = realpath('./');
//$absPath = /home/abc/domains/server2.abc.com/public_html/mockup
//$oldPath = /project_image/easy/Desert.jpg
$npath = $absPath."".$oldPath; //$oldPath is get by image element scr="xxx"
$npath will return this:
/home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg
When i unlink it
unlink($npath);
Then php return
No such file or directory in /home/../mockup/update_file.php -> point unlink($npath);
And i try to Hard Code it
$npath = /home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg
unlink($npath);
Then it will success.
I want to know how to use variable combine a new path to unlink it.
Sorry for my poor English
Are you sure your script is producing the exact same path? If you are building the path correctly and unlink is failing, you can try the shell instead. Sometimes this works like with samba mounts and what-not.
$absPath = realpath('./');
$npath = $absPath."".$oldPath;
// Bail if the path doesn't exist
if(!file_exists($npath)) die('Failed to build correct path');
// Try unlink via PHP
if(!unlink($npath) || file_exists($npath)) {
// PHP couldn't cut it, try unlink via shell
exec('rm ' . $npath, $output, $return);
if($return > 0)
die('Failed to delete file: ' . $npath);
}

Categories