phpmailer attaching two pdf files - php

I am using phpmailer for attaching pdf files and sending email with pdf attachments. One pdf file is being attached while the other is not being attached.
I am using the code as
$attachedfile = $_SERVER["DOCUMENT_ROOT"] . '/wp-content/plugins/xyz-user-registration/images/iraq_visa_form_test.pdf';
$mail->addAttachment($attachedfile, 'Visa Application');
$attachedfile2 = $_SERVER["DOCUMENT_ROOT"] . '/wp-content/plugins/xyz-user-registration/images/iraq_visa_form.pdf';
$mail->addAttachment($attachedfile2, 'Visa Application 2');
Only one pdf file is being attached other one is being attached.
It also works with single pdf file attatchment.
I have also use the following code
$attachedfile = array($_SERVER["DOCUMENT_ROOT"] . '/wp-content/plugins/xyz-user-registration/images/iraq_visa_form.pdf',$_SERVER["DOCUMENT_ROOT"] . '/wp-content/plugins/xyz-user-registration/images/iraq_visa_test.pdf');
foreach($attachedfile as $attachment){
$mail->AddAttachment($attachment);
}
But again it attachs one pdf file
please help

You mentioned that PHP returns 1 and nothing for the two calls to addAttachment. That's what PHP uses as text representation of true and false: One of your files is not readable by PHP, because the file is missing, the path is wrong, or it lacks sufficient ownership or permission. Double-check your paths and permissions.
When I say don't build your paths, I mean use only literal strings for the paths. You can write a standalone PHP script to check them:
<?php
$path1 = '/var/www/mysite/wp-content/plugins/xyz-user-registration/images/iraq_visa_form_test.pdf';
$path2 = '/var/www/mysite/wp-content/plugins/xyz-user-registration/images/iraq_visa_form.pdf';
var_dump($path1, is_file($path1), $path2, is_file($path2));
Check them in your shell too:
ls -al /var/www/mysite/wp-content/plugins/xyz-user-registration/images/iraq_visa_form_test.pdf /var/www/mysite/wp-content/plugins/xyz-user-registration/images/iraq_visa_form.pdf
If those are OK, go back to your original script and var_dump your generated paths, and compare them - including the length, in case you've accidentally included some non-printing or zero-width chars.

Related

Confused about pointing fopen to a specific file (which is using a variable filename) in a specific directory

So I'm basically creating .txt files with unique filenames and then changing the ext. of the file to .mobileconfig. That's the overall goal but I wanted the files in a different directory, that's not my root directory.
So it's basically an HTML form, then it takes the data submitted through that form, figures out what to do with it here:
<?php
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$genfile = fopen('./generated/'$UUID.'.txt', w);
file_put_contents('./generated/'$UUID.'.txt', $txt);
rename('./generated/'$UUID.'.txt', './generated/'$UUID.'.mobileconfig');
?>
I had it working, but it was in the same directory as my other files. I've tried the code above, I've tried it using " instead of '. I've tried without the period before the /, and I've tried without the ./ all together.
Is there anything else that I could try besides just moving the .php file to another directory because I do want to set something up where it deletes all the files inside the generated folder every x amount of time.
You have many syntax errors in your code.
Additionally, using file_put_contents() doesn't require that you open the file first.
Lastly, why create a file with a .TXT extension if you're going to rename it immediately afterwards?
Try this:
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$fname = "./generated/$UUID.mobileconfig";
file_put_contents($fname, $txt);
See the PHP manual for details on variable expansion in double-quoted strings

Changing file permissions in php

I'm a sysadmin for a small firm and I manage the server for them.
I've setup a portal for our customers to view their bills in pdf format, they are initially set with 0600 file permissions. For security reasons I cannot have all the pdf's 'visible' to everyone so I need a way to show them to the customer only when a pdf is clicked on the customers' account.
I have tried using the following, but it doesn't work and I'm getting a 'Forbidden' error...
chmod($filename, 0755);
echo "<td><iframe src='" . $filename . "' width=645 height=600 frameborder=0></iframe></td>";
chmod($filename, 0600);
The php script and the pdf files have the same owner set.
Any ideas what I'm doing wrong, I need to get this working?!
Many thanks! :)
This can not possibly work:
chmod($filename, 0755);
echo "<td><iframe src='" . $filename . "' width=645 height=600 frameborder=0></iframe></td>";
chmod($filename, 0600);
You're making the file readable only for the amount of time it takes PHP to echo that one line of HTML. I.e., by the time the user clicks the link, permissions have already been revoked again. On top of that, the file is world-readable for that period of time, so anybody on the Internet can see it.
To do this more securely, do not have the web server serve the files directly, as you will not be able to control who has access to them. Instead, put them outside the document root so that they can not be seen at all by the web server, and then proxy them through a PHP script (via readfile() or similar) that performs an ownership check.
In your script that generates the link:
echo 'PDF Download';
Where $fileId is some unique identifier for the file, but not the full file name.
Then, in download.php, something like this:
function getLoggedInUser() {
// return the logged-in user
}
function getFileForId($fileId) {
// get the full path to the file referenced by $fileId
}
function getOwnerOfFile($fileId) {
// get the user allowed to see the file referenced by $fileId
}
$fileId = $_GET['fileId'];
$file = getFileForId($fileId);
if (!file_exists($file)) {
header('HTTP/1.1 404 Not Found');
exit;
}
if (getLoggedInUser() !== getOwnerOfFile($fileId)) {
header('HTTP/1.1 403 Forbidden');
exit;
}
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="whatever.pdf"');
readfile($file);
[UPDATE]
and I have <a href="/viewbill.php?bid=<?php echo $invoice_number; ?>" title="View PDF Invoice"> where the $invoice_number is the name of the file.
That's fine, just make sure that viewbill.php performs a check to ensure that the logged-in user is the same as the user that the bill is for, otherwise any customer can view any other customer's bills simply by changing the invoice number in the URL.
When you say 'put them outside the document root' where do you mean exactly;
Let's say that your Apache document_root directive points to /var/htdocs/public/. In this case, everything in that directory and everything under it can be seen by Apache and potentially served directly to a client. E.g., if you have a PDF file in /var/htdocs/public/pdfs/12345.pdf then a user can simply request the URL /pdfs/12345.pdf in their browser, regardless of what PHP structures are in place. Often this is mitigated with the use of .htaccess files but this is not ideal. So, if you have files that you want to keep controlled, you should not put them anywhere under the document_root. For example, put them in /var/htdocs/docs/ instead. This way, Apache can not possibly see them, but you can still use readfile() to pull their contents.

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.

php output directory was not found

I'm trying to save a file inside php: // output to send it as an answer (it's an excel).
The problem is that php does not find the directory, according to the documentation should be able to access it.
i add this validation to my code:
$folderName = 'php://output';
if(!is_dir($folderName)){
throw new FileNotFoundException($folderName . " directory not found.");
}
$objWriter->save($filePath);
and the exception has been throwed and return me:
"php://output directory not found.",
php://output is not a directory; it's an output stream. You use php://output to write stuff to the output buffer the same way echo or print does. For example, if you wanted to force the browser to display a PDF or an image straight away without saving it first, you would use php://output.
If you wanted to physically save the file in your filesystem then a proper path must be used.

Check for file with same filename, but different extension

I have a directory contain jpeg and raw image files. Some jpeg files have a raw file version of them, some don't. Luckily, if a jpeg has a raw file they are named the same (excluding the extension). So, I need a way to check this directory for a matching raw file of the same filename, exclusing file extesion. the raw file, file extension could be pretty much anything.
Any ideas how I can do this? I have the filename (excluding extesion) stored of $filename at the moment.
To explain further. I have a directory with the following files in it:
cat.jpg
dog.jpg
bird.jpg
cat.raf
dog.foo
I need to match cat.jpg to cat.rag and dog.jpg to dog.foo. These have just been extracted from a uploaded zip file.
Try searching for files starting with the same name:
$fileWithoutExtension = basename($filename, '.jpg');
$allFilesWithThisName = glob($fileWithoutExtension . '.*');
if (count($allFilesWithThisName)) {
echo 'There is another file with this name';
}
As you already have the filename w/o the extension, you can just check if the raw file exists (file_exists()):
if (file_exists($filename.'.raw')) {
echo 'RAW file exists:', $filename , "\n";
}
But this seems so trivial to me, that I might did not understood your question completely.

Categories