PDF in PHP ZipArchive throwing errors, server permissions [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am collecting a number of files from the server and generating a ziparchive with PHP. All goes super well until I download the zip archive and try to open the file. The reader throws an exception "File type plain text document (text/plain) is not supported". The file is named correctly (c102.pdf). I presume the mime type of the file is getting messed up some how, but I'm not quite sure.
php version 5.4.37
I should note that I'm using ubuntu 14.04 locally and my reader is the default document viewer, however, it does read the file correctly before upload.
follow up - Could this be a permissions issue? the "downloads" directory is set to 777, while the new zip files created within it are 644. Its as if "blank" files are being placed in the zip archive (the total size of the zip is 1.6k and should be at least a few hundred).
Another follow up - the following previous posts discuss the chmod issue
PHP: generated zip has chmod 644 and how to set permission 777 to a zip file? . The chmod() method is not working for me however - chmod() fails to execute on the server (I've amended the code below). We will see what technical support has to say.
Answer in this case.....
After speaking to Customer Support - the reason none of this is working is because I'm on a shared hosting account. The chmod() function is restricted and should otherwise work.
My saga continues...
I now have a LAMP stack on an EC2 instance and just when I thought I was boss - I remain in the same bind. My program generates a zip file in the correct directory - with all the appropriate file names - but the files are empty. I am still thinking this is an ownership / permissions issue. SO, some follow up questions...
The folders on the web server are owned by "Ubuntu", yet the newly created files are owned by "www-data". So, who is "www-data"? is it Apache or PHP? is PHP also Apache? why cant I chmod() the files after their created so they aren't 644? Is the files status of the zip as 644 the reason I can't write to them? Can I force newly created files in a directory to have different ownership or a particular set of permissions?
if (isset($_GET['getzip'])) {
$issuedsetid = $_GET['getzip'];
$time = mktime();
$sql = "SELECT * FROM issuedsets WHERE id=$issuedsetid";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$packid = $row['packid'];
$sheets = $row['sheets'];
$sheets = explode(",",$sheets);
}
}
$sql = "SELECT * FROM pname WHERE id=$packid";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$packname = $row['name'];
}
}
// create the zip file
$path = "/home/marekfalkowski/public_html/index/downloads/".$packname."_" . $time . ".zip";
$zip = new ZipArchive();
// Open a new zip file
$zip->open($path, ZipArchive::CREATE);
if (chmod($path,0777)){
echo "chmod succesful";
} else {
echo "not succesful";
}
foreach($sheets as $sheet){
// the saved file name as it exists on the server...
$file = $sheet.".pdf";
// the new name of the file...
$sql = "SELECT * FROM files WHERE id=$sheet";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$filename = $row['number']."-".$row['name'].".pdf";
}
}
// add the files
if (file_exists("/home/marekfalkowski/public_html/index/uploads/".$file)) {
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$files, $filename);
} else {
echo "not there";
}
}
$zip->close();
}

This was a silly mistake. This line:
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$files, $filename);
needs to be changed to this:
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$file, $filename);
What a waste of time this has been. It works now.

Related

DS_Store file is created on ZipArchive::extractTo

I'm creating a PHP script, which supposed to extract a zip archive stored on the php file directory to a folder.
Everything works well, but when I check te result, I find 2 folders under the directory: a folder with the name of the zip archive, and another folder named __MACOSX. I don't know how this folder came there, especially as I'm using Windows 7. Second, in each folder there is a file called .DS_Store.
Now, I don't know how these things got there. This is my code:
$zip = new ZipArchive;
if ($zip->open('File.zip')) {
$path = getcwd() . "/details/" . trim($id) . "/";
$path = str_replace("\\","/",$path);
echo $path;
echo $zip->extractTo($path);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
This is the only code that extracts the zip file, or touching it, and as you can see, there is nothing like __MACOSX or .DS_Store.
Can you please help me?
File.zip originated on a OSX system. __MACOSX and .DS_Store have 0 usage or bearing on any other OS. Delete / Ignore them and keep trucking.
As an aside, you may want to add the stated file system objects to your project .gitignore.
https://superuser.com/questions/104500/what-is-macosx-folder
https://en.wikipedia.org/wiki/.DS_Store

Setting destination for secure file uploads php

I am using the following php file upload class to upload my files in relative security. I'll be adding more security features later:
http://www.verot.net/php_class_upload.htm
My problem is though, I would like to upload my file to the folder www.mysite.com/upload which I've already pre-created ready to take the files.
The only problem is I don't know how to set it properly to do that. I've confirmed the form is submitting fine. Here's what I tried to use:
$handle = new class_upload($_FILES['image_upload']);
if ($handle->uploaded) {
$handle->file_new_name_body = 'image_resized';
$handle->image_resize = true;
$handle->image_x = 100;
$handle->image_ratio_y = true;
$handle->process('/home/user/upload');
if ($handle->processed) {
echo 'image resized';
$handle->clean();
} else {
echo 'error : ' . $handle->error;
}
}
I get the error:
"Destination directory can't be created. Can't carry on a process."
What do I set for $handle->process('/home/user/upload'); so that it will upload into the correct directory?
The error message suggests that the user your webserver is running under may not have permissions to create directories... so it would imply the directory you've created is not being targeted.
You'll need full path to this folder... one way to get it would be to use:
$handle->process($_SERVER['DOCUMENT_ROOT'] . '/upload/');
I'd try and avoid this though as the $_SERVER variable can be tampered with or can be inaccurate in general.
The better approach imho would be:
$handle->process(realpath(dirname(__FILE__) . '/upload/');
And ensure the folder you've created has writable permissions for the web-server's user/group.
I suspect, what you are looking for is $handle->process(dirname(__FILE__).'/home');, assuming the calling script is directly in the web root folder.

Uploading files in PHP - Unzipping and Moving

I have a very basic, very straightforward function that takes a file (after checking it to make sure its a zip among other things) and uploads it, unpacks it and such:
public function theme(array $file){
global $wp_filesystem;
if(is_dir($wp_filesystem->wp_content_dir() . "/themes/Aisis-Framework/custom/theme/")){
$target_path = $wp_filesystem->wp_content_dir() . "/themes/Aisis-Framework/custom/theme/";
if(move_uploaded_file($file['tmp_name'], $target_path . '/' . $file['name'])) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo($target_path); // change this to the correct site path
$zip->close();
//unlink($target_path);
}
$this->success('We have uplaoded your new theme! Activate it bellow!');
} else {
$this->error('Oops!', 'Either your zip is corrupted, could not be unpacked or failed to be uploaded.
Please try again.');
}
}else{
$this->error('Missing Directory', 'The Directory theme under custom in Aisis Theme does not exist.');
}
if(count(self::$_errors) > 0){
update_option('show_errors', 'true');
}
if(count(self::$_messages) > 0){
update_option('show_success', 'true');
}
}
Extremely basic, yes I have used my target path as both the path to upload too and unpack (should I use a different path, by default it seems to use /tmp/tmp_name)
Note: $file is the array of $_FILES['some_file'];
My question is I get:
Warning: move_uploaded_file(/var/www/wordpress/wp-content//themes/Aisis-Framework/custom/theme//newtheme.zip): failed to open stream: Permission denied in /var/www/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/FileHandling/Upload/Upload.php on line 82
Warning: move_uploaded_file(): Unable to move '/tmp/phpfwechz' to '/var/www/wordpress/wp-content//themes/Aisis-Framework/custom/theme//newtheme.zip' in /var/www/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/FileHandling/Upload/Upload.php on line 82
Which basically means that "oh the folder your trying to move from is owned by root, no you cannot do that." the folder I am moving too is owned by apache, www-data. - I have full read/write/execute (it's localhost).
So question time:
Should my upload to and move to folder be different?
How, in a live environment, because this is a WordPress theme, will users who have the ability to upload files be able to get around this "you dont have permission"?
You should try to do it the wordpress way. Uploading all user content to wp-content/uploads, and doing it with the native functions.
As you mention, uploading to a custom directory, may be an issue to non tech savvy users. /uploads already have the special permissions.
Check out wp_handle_upload. You just have to limit the mime type of the file.
The path you are trying to upload is some where wrong here
wp-content//themes
try removing one slash

Can't create a zip file with PHP

I've created the following code to create a zip file. I'm pulling a list of files from the database depending on the $job_number (which I'm getting from the global $_GET array) and then trying to add them to the zip file.
That part is working fine. It's pulling the list of files from the database, as I can see by echoing or dumping with print_r the results.
The only problem is that the .zip file isn't being created at all. I can't see where I've gone wrong.
$sth = $conn->prepare('SELECT `dp_filename` FROM damage_pics WHERE dp_job_number = :job_number');
$sth->bindParam(':job_number', $job_number);
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$zip = new ZipArchive();
$zip->open('example5.zip', ZipArchive::CREATE);
$result = $sth->fetchAll();
echo '<pre>';
print_r($result);
foreach ($result as $file)
{
// just echoing for testing purposes to see if file name is created correctly.
$image = $file['dp_filename'];
echo $image . "<br />";
$zip->addFile("uploads/{$image}");
}
$zip->close();
Sounds like your PHP script is being run with insufficient permissions to write to the destination directory. I did some experimenting, and in such a situation the $zip->open() call would silently fail with no indication of what went wrong.
You could put the following code at the top to determine if this is indeed the problem:
$fp = fopen('example5.zip', 'w');
if ($fp === FALSE) { die("Cannot open example5.zip for writing"); }
fclose($fp);
To fix the issue, I would suggest using an absolute path and filename (such as /tmp/example5.zip) and then make sure that the destination directory is writable by the user that's executing the script (likely whatever user is running the HTTP server software, such as www-data or httpd, depending on the OS and distribution).

Issues of Parse Email and Save Attachments into directory

I am using this script(http://stuporglue.org/mailreader-php-parse-e-mail-and-save-attachments-php-version-2/) to save email attachment on my server. You can also view the complete script on browser here: http://stuporglue.org/downloads/mailReader.txt
Everything works fine but there are 2 problems here.
1) The file name of the image that i saved into the directory is not an image: 1360341823_test_jpg
How to convert the file name from 1360341823_test_jpg to 1360341823_test.jpg
in the script?
2) The permission of the file that saved in the directory is 600.
How to make it default 755 or 775?
I believe this is the function to convert the image in the script.:
function saveFile($filename,$contents,$mimeType){
global $save_directory,$saved_files,$debug;
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time()."_".$filename;
while(file_exists($save_directory.$name)) {
$name = time()."_".$filename;
}
// Attempt to lock
$outfile = fopen($save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
} else {
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
// This is for readability for the return e-mail and in the DB
$saved_files[$name] = Array(
'size' => formatBytes(filesize($save_directory.$name)),
'mime' => $mimeType
);
}
Any help?
The original script used the data to store in the DB but I think you are trying to save it in the file. You are creating the file without extension here:
// Attempt to lock
$outfile = fopen($save_directory.$name,'w');
Either add the .jpg after the line as:
#outfile.=".jpg";
Other way if you don't want to change script then you can get use as:
$contents = file_get_contents($save_directory.$name);
$outfile = fopen($save_directory.$new_name,'w');
write($outfile,$contents);
fclose($outfile);
This would resolve your first problem and for second question kindly use the FTP or Control panel provided to access the files to change the ownership rights. If you don't know about any thing then you contact your Web Hosting Service Provider to share the ownership from 755 to 775

Categories