curl or file_get_contents needs full url path - php

I use this code to generate a QR Code and display it:
<?php
$aux = 'qr_img0.50j/php/qr_img.php?';
$aux .= 'd=Text&';
$aux .= 'e=H&';
$aux .= 's=4&';
$aux .= 't=P';
?>
<img width="250" src="<?php echo $aux; ?>" />
It generates and displays it without problems,
but I don't want to display it, but load it into "dompdf" (PHP PDF Generator).
I found out, that I can't give dompdf the "$aux" variable ("< img src='$aux' />"). The variable returns the correct string, but dompdf can't display it (Probably due to being a PHP file).
I came up with file_get_contents, but surprisingly, it returned a blank file.
I used:
file_put_contents('tempqr.png', file_get_contents($qrc));
It is not due to wrong permissions, because...
when I typed the entire URL path, it 'copied' the file successfully (http://localhost:2180/work/qr_img0.50j/php/qr_img.php?...), but I think that's not a reliable solution, because of the port and stuff that can change over time. I installed cURL, and the same issue persists: It only displays with the full URL path. I tried fopen to 'read' the image into a buffer, and the buffer remained blank.
Maybe anyone can help me (and other readers), to get those two functions to load the file (maybe without the whole http unreliable thing?).
Or maybe there's another way to generate images from "qr_img0.50j" without calling php that I didn't know...

Dompdf (as of 0.6.1) will no longer parse PHP in your document. You will need to do that prior to passing the document to Dompdf. Probably the easiest method to do this is to render the image and insert it into the document as a data-uri.
You may have to modify your QR generator to work in this flow if it's not designed for command-line execution. Ideally it would just be a callable function, which is what I presumed for the sample.
With Dompdf 0.7.x:
<?php
// require dompdf autoloader, then ...
using Dompdf\Dompdf;
$image = qr_img('Text', 'H', '4', 'P'); // assumine PNG output
$html = '<img width="250" src="data:image/png;base64,' . base64_encode($image) . '" />';
$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream();
?>
FYI, the same issue applied to file_get_contents. It does not parse the PHP of a file. It can only be used to get the file itself.
Regardless of the particular method you use to get a file the results depend on the source. Files retrieved from the local file system will not have their PHP parsed. Files retrieved via a web server will.

Related

How to load PDF from local fileserver as a block element on a local webserver using PHP?

Background
I am working on setting up an intranet webpage where the user can select an item from a list, and it will display information about that item and a PDF as a block element.
The PDFs will need to be updated and replaced by specific people, so they are stored on a separate file server on the internal network.
HTML Solution Attempt
I've tried using
<embed src="file:///myFileServer/PDFs/filename.pdf" width="1000" height="600" type="application/pdf">
but I get local resource errors:
Firefox: "Security Error: Content at myWebServer/file_read.php may not load or link to file:///myFileServer/PDFs/filename.pdf."
Edge/Chrome: "Not allowed to load local resource: file:///myFileServer/PDFs/filename.pdf"
I understand the error is because the PDF path is loaded by the browser, not the web server. This likely would be a problem even if it was allowed, because not all of the users would have access to the file server. Naturally, my next thought was to try using PHP to display the element so that the browser never needs to see a file path and the web server loads the PDF.
PHP Solution Attempt
I then tried using
<?php
$filename = "file:///myFileServer/PDFs/filename.pdf";
header("Content-type: application/pdf");
header("Content-Length: " . filesize($filename));
readfile($filename);
?>
This gave me the following warning, which had to do with the PHP that is used to load the page's navigation bar.
"Cannot modify header information - headers already sent by (output started at C:\Apache24\htdocs\nav.php:66) in C:\Apache24\htdocs\file_read.php on line 81"
Removing <?php include 'nav.php' ?> in the file_read.php caused the PHP code mentioned above to work, but not as I wanted. It basically loads a full-page PDF view as if you selected a PDF to open it in the browser, instead of displaying it as a page element.
PHP PDF to Base64 Solution
Since the above did not work, I kept digging for a solution. It's a little hacky, but I did find one solution that seems to works.
<?php
$fileLocation = "//myFileServer/PDFs/filename.pdf";
$pdf = chunk_split(base64_encode(file_get_contents($fileLocation))); //Convert to Base64
echo '<embed src="data:application/pdf;base64,' . $pdf . '" style="height:500px;width:80%;" title="test"></embed>';
?>
While this does work and the code is rather clean, it's a bit slow and I feel like there has to be a more efficient way to do this.
My Question
Is there a better way to deal with the limitations of loading a local resource from another internal server than converting the PDF to Base64?

display image from HTML page using PHP without calling PHP script or using PHP echo to hide image path

I want to display images, from files, in an HTML webpage, using PHP to hide the location of the files, using PHP header/readfile, and avoiding any PHP that would reveal the file location (such as echo).
So far I've only been able to get this working by calling a PHP scrpit from the HTML, but would prefer to do so without calling a script, so a viewer has no sight of the PHP script file. I do not want to use a PHP file rather than HTML file (so a viewer couldn't type the URL of the PHP script in themselves).
image.php:
<?php
header('Content-Type:image/jpeg');
readfile('../image.jpg');
?>
image.html:
<html>
...
<img src="image.php"/>
In the HTML file I would like to do the equivalent but in-line:
<html>
...
<img src="<?php header('Content-Type:image/jpeg');readfile('../image.jpg');?>"/>
Or:
<html>
...
<?php
echo '<img src="';
header('Content-Type:image/jpeg');
readfile('../image.jpg');
echo '"/>';
?>
I suspect my lack of understanding of how HTML and PHP work together is letting me down here.
I would like to do the equivalent but in-line:
You cannot. You must have separate request. You could optionally inline the image as base64 but that bad idea anyway.
Also this code looks like pointless - you just exposing existing file w/o any benefit of doing that yourself BUT with the penalty of killing all the caching and other features browsers could do. Unless you know how to do that properly (this is not that trivial), you are complicating simple thing instead of simplifying complicated.
What you want can not be done as you're trying. You can echo the contents via the base64 aproach. but that would make your html grow in size very rapidly, which isnt good for performance.
There is a way you can get it to work though. It's a bit trickier, but you can use your .htaccess file for this. Normally you often use it to rewrite some url to redirect the url to the index.php. You can also use it to create an image url:
RewriteEngine On
RewriteRule ^/special-images/(.*)\.jpg$ /php-file-directory/image.php?image-name=$1 [L]
If you now do <img src="/special-images/bob.jpg" /> it will internally open-image.php with $_GET['image-name'] being bob.
*Cant test the htaccess right now, but you get the gist of it.
try coverting it to a data url
https://stackoverflow.com/a/13758760/11485791
example:
<img src="<?
php path = '../image.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>"/>
but then the returned html would be huge

(Inline) PHP in domPDF 7.0

I switched from TCPDF to domPDF because it seems more convenient to handle when creating invoices from html to pdf (I am rather a low pro on PHP :)). Now that I created the html file as a PDF file I recognized it does not output any PHP in the PDF - since the data from my sql databanks should fill the PDF it is kinda a problem.
I saw that you can enable PHP in the options.php included in the src-folder and I tried to do like it is written in the manual (and also tried various other code lines) but it just doesn't want to work:
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
require_once ("$root/../xxx/dompdf/autoload.inc.php");
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->setIsPhpEnabled('true');
$dompdf = new Dompdf($options);
$dompdf->loadHtml(file_get_contents("testdomhtml.php"));
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("bla",array("Attachment"=>0));
The PDF is shown but without the input from any PHP code.
If someone would be so kind, I would also be interested in knowing why and in how far enabling PHP is a security risk since I actually want to use that for my business. Would it be more advisable to wrap it all up in the main php file without loading external html and css files?
Thanks a lot in advance!
You could do something like this (not tested the code). Replace
$dompdf->loadHtml(file_get_contents("testdomhtml.php"));
With
ob_start();
include 'testdomhtml.php';
$output = ob_get_clean();
$dompdf->loadHtml($output);
More options How to execute and get content of a .php file in a variable?
Your file_get_contents("testdomhtml.php") will get actual content of file and will not execute any code inside it. Instead make it web accessible and pass URL to this page:
$dompdf->load_html_file('http://yourdomain.ext/testdomhtml.php');

dompdf and php (mysql data)

I would like to pull data from a mysql db.
This data is then inserted into a html file which is then converted to a pdf using dompdf.
The template is perfect and display's well when I run call dompdf.
However as soon as I try and insert php code, the template still shows perfectly, how ever the php code is displays nothing. If I open the page its shows, so I know it works.
In the options file I have done this :
private $isPhpEnabled = true;
my php file to call the template (LeaseBase.php):
<?php
$options = new Options(); $options->set('isPhpEnabled','true');
$leasefile = file_get_contents("Leases/LeaseBase.php");
$dompdf = new Dompdf($options); $dompdf->loadHtml($leasefile);
$dompdf->stream(); $output = $dompdf->output(); file_put_contents('Leases/NewLeases.pdf', $output);
?>
I also can't seem to pick up anything in the log files.
Any assistance is appreciated
However as soon as I try and insert php code, the template still shows
perfectly, how ever the php code is displays nothing.
Answer: It shows nothing because when a php page is executed, it outputs html (and not the php code). If you don't have an echo or print or any code that generates html code from the php script, the page will in fact be blank.
It's important to remember that php is serverside code WHICH CAN generate html code as long as you instruct it accordingly.
With versions of Dompdf prior to 0.6.1 you could load a PHP document and the PHP would be processed prior to rendering. Starting with version 0.6.1 Dompdf no longer parses PHP at run time. This means that if you have a PHP-based document you have to pre-render it to HTML, which does not happen when using file_get_contents().
You have two options:
First: Use output buffering to capture the rendered PHP.
ob_start();
require "Leases/LeaseBase.php";
$leasefile = ob_get_contents();
ob_end_clean();
Second: Fetch the PHP file via your web server:
$leasefile = file_get_contents('http://example.com/Leases/Leasebase.php');
...though, actually, if I were loading the file into a variable and feeding it to dompdf without doing any further manipulation I would use dompdf to fetch the file instead. In this way you are less likely to have to deal with external resource (images, stylesheets) reference problems:
$dompdf->load_html_file('http://example.com/Leases/Leasebase.php');

Glass Mirror API save attatchment image to server via PHP

I am using the PHP quick start project example to display the timeline's attachment (image):
<?php
if ($timeline_item->getAttachments() != null) {
$attachments = $timeline_item->getAttachments();
foreach ($attachments as $attachment) { ?>
<img src="<?php echo $base_url .
'/attachment-proxy.php?timeline_item_id=' .
$timeline_item->getId() . '&attachment_id=' .
$attachment->getId() ?>" />
<?php
}
}
?>
Now I need to save the image to the server so I can resize it and use it elsewhere.
I have tried a few variations of file_put_contents, fopen, and curl but it seems attachment-proxy.php is not returning the image in a format that any of these expect.
How can save a Timeline Attachment to my server?
SOLUTION: Based on Prisoner's response I took another look at the attachment-proxy.php file. It is returning the image as a string. I had unsuccessfully tried file_put_contents($img, file_get_contents("attachment-proxy.php....")); before.
Turns out I don't need the file_get_contents() part.
I altered the last few lines of attachment-proxy.php to this:
$img = $_GET['timeline_item_id'].'.jpg';
$image = download_attachment($_GET['timeline_item_id'], $attachment);
file_put_contents($img, $image);
It works. It saves the image to my server with the ID as the file name.
Thanks.
Have you checked to see what it is returning? The attachment_proxy.php requires OAuth to have been completed, and will redirect you through the OAuth flow if this hasn't been done. So it may very well be that it is saving the HTML for the OAuth login page, or the information from the redirect page.
However, if you're trying to setup something on your server that calls your own server's attachment_proxy.php page... you're jumping through additional unnecessary hoops.
You can probably take a look directly at attachment_proxy.php to see how it is getting the attachment data from Google's servers, and then use this same method to get them and store them on your server instead of just feeding it out for the img tag. Looking at https://github.com/googleglass/mirror-quickstart-php/blob/master/attachment-proxy.php it seems like most of the work is done in a call to download_attachments() which is located in https://github.com/googleglass/mirror-quickstart-php/blob/master/mirror-client.php. You should be able to either borrow the code from download_attachments() or call it directly yourself.

Categories