mpdf generates blank page - php

So i am having difficulties trying to generate pdf from URL using mpdf
code :
<form action="generate.php" method="POST">
url: <input type="text" name="url"><br>
<input type="submit">
</form>
generate.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$url = test_input($_POST["url"]);
$pdf=file_get_contents($url);
include('mpdf60/mpdf.php');
$mpdf=new mPDF();
$mpdf->debug = true;
$mpdf->WriteHTML($pdf);
$mpdf->Output();
exit;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Returns no errors , just blank pdf page .

I got same problem with mPDF 5.6. When I used xdebug I found these 2 lines:
$str = #preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str);
$str = #preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);
As you can see there is "#" char that blocking errors output. So if you have php >=7.0 you will never get error about "e" modifier that was deprecated. So all your HTML will be NULL after these lines.
I updated this function:
// mpdf/includes/functions.php
if (!function_exists('strcode2utf')) {
function strcode2utf($str,$lo=true)
{
//converts all the &#nnn; and &#xhhh; in a string to Unicode
if ($lo) { $lo = 1; } else { $lo = 0; }
// Deprecated modifier "E" in preg_replace
//$str = #preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str); // blocked errors output!! wtf?
//$str = #preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);
$str = preg_replace_callback('/\&\#([0-9]+)\;/m',
function($num) use ($lo) {
return code2utf($num, $lo);
}, $str);
$str = preg_replace_callback('/\&\#x([0-9a-fA-F]+)\;/m',
function($num) use ($lo) {
return codeHex2utf($num, $lo);
}, $str);
return $str;
}
}

Yo haven't specified much about the url input that is being given.I hope the url is pointing to the same server.Else mpdf will show error
There is nothing wrong with your code.Please check for any file permission issue.

Related

PHP - How remove blank line where placeholder used to be?

I came across this old post while searching for a way to efficiently replace placeholders in a template file.
Everything seems to be working however, there are some values which are optional and the best I've been able to do is replace the placeholders with empty strings, which still leaves blank lines.
The current code I'm testing with is below:
test.php:
<?php
$text = file_get_contents('test.html');
$pattern = '/{{{([a-zA-Z0-9_]+)}}}/';
$text = preg_replace_callback($pattern, 'produce_replacement', $text);
echo $text;
function produce_replacement($match) {
$producerName = 'evaluate_'.strtolower($match[1]);
return function_exists($producerName) ? $producerName() : null;
}
function evaluate_test1() {
ob_start();
include'test_include.php';
$test4 = ob_get_clean();
return $test4;
}
function evaluate_footer() {
if (isset($blah)) {
$val = 'some string';
} else {
$val = '';
}
return $val;
}
?>
test.html (template file):
<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}
</body>
</html>
test_include.php:
<?php
$a = 'Hi, ';
$b = 'jeff!';
echo $a.$b;
?>
So {{{footer}}} will be replaced with $val which will be either some string or a blank line will remain. How can I get rid of that blank line?
Your code is working as expected. The newline character exists in your template file, you need to update it:
<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}</body>
</html>
However I don't see the problem with that whitespace, a browser would not render it anyway.

Php remove html tags when reading a page

I have a script to read Shoutcast live broadcast informations.
I am getting name of track and searching it on spotify api to get cover art.
My code:
$sc_url_ip = "streamip";
$sc_url_port = "streamport";
function getNowPlaying($sc_url_ip,$sc_url_port)
{
$open = fsockopen($sc_url_ip,$sc_url_port,$errno,$errstr,'.5');
if ($open) {
fputs($open,"GET /7.html HTTP/1.1\nUser-Agent:Mozilla\n\n");
stream_set_timeout($open,'1');
$read = fread($open,200);
$text = explode(",",$read);
if($text[6] == '' || $text[6] == '</body></html>'){
$msg = ' live stream offline'; }
else {
$msg = $text[6];
}
$text = $msg;
}
else {
return false;
}
fclose($open);
return $text;
}
$current_song = getNowPlaying($sc_url_ip,$sc_url_port);
echo $current_song;
But when searching with spotify api, my track name look like this in source code:
Pink Floyd - Welcome to the Machine</body></html>
Because of html tags, spotify api search results zero. See search url:
https://api.spotify.com/v1/search?query=Pink+Floyd+-+Welcome+to+the+Machine%3C%2Fbody%3E%3C%2Fhtml%3E%3B&type=track
I tried strip_tags but I couldnt.
How can I remove these </body></html> tags from $current_song ?
The variable $current_song contains the html tag right? Then to remove it, try this:
$current_song = strip_tags(getNowPlaying($sc_url_ip,$sc_url_port));

How to use the content-disposition header to set a downloaded UTF-8 filename?

I am storing my files on Amazon Cloud Drive. And there are option for setting response-content-disposition to direct links from Amazon.
From the API:
response-content-disposition: (Optional) If specified, the content-disposition of the response will be set to this value
I need to set it download mp3 files. I don't need to play it on browser.
And I want to set downloaded file name: Эльбрус Джанмирзоев - Кавказская любовь.mp3
I tried many ways... Urlencode... Urlencode + http build query etc...
But now the result is: Эльбрус+Джанмирзоев+-+Кавказская+любовь.mp3 when downloading files.
And here is my php code:
<?php
function file_generate_download_link($filename = false, $force = true)
{
$json['tempLink'] = 'https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb';
$url = $json['tempLink'];
if($force)
{
$data['download'] = 'true';
}
if($filename)
{
$data['response-content-disposition'] = ' attachment; filename*=UTF-8\'\''.urlencode($filename).'';
}
if(isset($data)) {
$data = http_build_query($data);
$url .= '?' . $data;
}
return $url;
}
echo file_generate_download_link($filename = 'Эльбрус Джанмирзоев - Кавказская любовь.mp3');
?>
This code returns me this link:
https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb?download=true&response-content-disposition=+attachment%3B+filename%2A%3DUTF-8%27%27%25D0%25AD%25D0%25BB%25D1%258C%25D0%25B1%25D1%2580%25D1%2583%25D1%2581%2B%25D0%2594%25D0%25B6%25D0%25B0%25D0%25BD%25D0%25BC%25D0%25B8%25D1%2580%25D0%25B7%25D0%25BE%25D0%25B5%25D0%25B2%2B-%2B%25D0%259A%25D0%25B0%25D0%25B2%25D0%25BA%25D0%25B0%25D0%25B7%25D1%2581%25D0%25BA%25D0%25B0%25D1%258F%2B%25D0%25BB%25D1%258E%25D0%25B1%25D0%25BE%25D0%25B2%25D1%258C.mp3
If I enter this link Chrome saves this file with this name:
Эльбрус+Джанмирзоев+-+Кавказская+любовь.mp3
But I need excatly save file with this name:
Эльбрус Джанмирзоев - Кавказская любовь.mp3
Where is my mistake?
Gotcha! I need to use rawurlencode function!
So the right code is:
<?php
function file_generate_download_link($filename = false, $force = true)
{
$json['tempLink'] = 'https://content-na.drive.amazonaws.com/cdproxy/templink/iTwUqoQ3cJXOpj6T8SCDmKwtF37TAENiSLQzy7pTSbkFfJttb';
$url = $json['tempLink'];
if($force)
{
$data['download'] = 'true';
}
if($filename)
{
$data['response-content-disposition'] = ' attachment; filename*=UTF-8\'\''.rawurlencode($filename).'';
}
if(isset($data)) {
$data = http_build_query($data);
$url .= '?' . $data;
}
return $url;
}
echo file_generate_download_link($filename = 'Эльбрус Джанмирзоев - Кавказская любовь.mp3');
?>

Text problem in template machine

I have this code:
class template
{
public $template,$prefix,$replace;
function __construct($template, $prefix)
{
$this->prefix = $prefix;
$this->template = $template;
}
public function SetValue($name, $replace)
{
$this->replace["#".$name."#"] = $replace;
}
public function Tempclude($found)
{
$file = "styles/main/".$found[1].'.html';
if(!file_exists($file))
exit("the template '" . $found[1] . "' wasn't found.");
return file_get_contents($file);
}
public function finish($stream = "normal")
{
if($stream == "folder")
$code = file_get_contents("../styles/main/".$this->template.".html");
else
$code = file_get_contents("styles/main/".$this->template.".html");
$code = preg_replace_callback("#<pb:include=\"(.*)\">#iuU", array($this, 'Tempclude'), $code);
if(is_array($this->replace))
$code = str_replace(array_keys($this->replace), $this->replace, $code);
$code = str_replace("\r\n", "", $code);
$code = str_replace(" ", "", $code);
echo $code;
}
}
If I type in the Template some simple text, the page turns white with nothing inside.
What is the problem?
it is no the problem.
Try doing this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
and index.html:
<pb:include="header">
hhh
#Slider#
<pb:include="footer">
its work.
if you change index.html to:
<pb:include="header">
<div id="hh">
hhh
</div>
#Slider#
it return a white list with somthing inside.
I have found the unquoted constant shows warning (depends on php configuration, WAMP does)
In the edited code that you have problem with errors, only quote the two constants in the begining it should work okay, test it like this:
$template = new template("index", "");
$template->SetValue("notice", "notice:");
$template->finish();
folder structure: styles/main must be provided. These files must be found inside main: index.html, footer.html, header.html must be privided
When everything okay, please try to delete any uneccessary comments or answers.
Thank you!

Problem with inserting an image in a form using GD!

I'm trying to develop a captcha class for my website everything was doing fine until I tried to embed the image generated with PHP GD inside my subscription form!
Here is the code of my class:
<?php
//captcha.php
header("Content-type: image/png");
class Captcha {
// some attributes bla bla
public function __construct($new_string_length,$new_width_picture,
$new_height_picture,$new_string_color) {
$this->string_length = $new_string_length;
$this->width_picture = $new_width_picture;
$this->height_picture = $new_height_picture;
$this->string_color = $new_string_color;
}
public function getString() {
return $this->string;
}
public function generateRandomString() {
$str = "";
$basket = "abcdefghijklmnopqrstuvwxyz0123456789";
$basket_length = strlen($basket);
srand ((double) microtime() * 1000000);
for($i=0;$i<$this->string_length;$i++) {
$generated_pos = rand(0,$basket_length);
$str_substr = substr($basket,$generated_pos-1,1);
if(!is_numeric($str_substr)) {
// if the character picked up isn't numeric
if(rand(0,1)==1) {
// we randomly upper the character
$str_substr = strtoupper($str_substr);
}
}
$str = $str.$str_substr;
}
$this->string = $str;
}
**public function generatePictureFromString($new_string) {
$root_fonts = '../fonts/';
srand ((double) microtime() * 1000000);
$list_fonts = array('ABODE.ttf','acme.ttf','Alcohole.ttf',
'Anarchistica.ttf','AMERIKAA.ttf');
$image = #imagecreatetruecolor($this->width_picture,$this->height_picture);
$noir = imagecolorallocate($image,0,0,0);
$clr = explode('/',$this->string_color);
$clr = imagecolorallocate($image,$clr[0],$clr[1],$clr[2]);
for($i=0;$i<strlen($new_string);$i++) {
imagettftext($image,rand(($this->height_picture/4.3),($this->height_picture)/4.2),
rand(-45,45),($this->width_picture)/(5*$this->string_length)+($this->width_picture)/($this->string_length)*$i,0.6*($this->height_picture),$clr,
$root_fonts.$list_fonts[rand(0,count($list_fonts)-1)],substr($new_string,$i,1));
}
imagepng($image);
imagedestroy($image);
}**
}
I willingly avoided to show some useless part of the class. The class itself works perfectly when I call the generatePictureFromString(..) method like this:
<?php
//testeur_classe.php
require_once '../classes/captcha.php';
$captcha = new Captcha(5,200,80,"255/255/255");
$captcha->generateRandomString();
$str = $captcha->getString();
$captcha->generatePictureFromString($str);
?>
But when I try to insert the picture generated in my form using:
<img src="<?php echo PATH_ROOT.'classes\testeur_classe.php'; ?>"/>
nothing is displayed!
How am I supposed to do that ?
Thank you!
OK: What do you see if you open classes\testeur_classe.php in the browser?
(p.s. the same question as Ryan Graham asked you in question comment)
OK: I think you must set correct headers before picture output like:
header('Content-type: image/png');
p.s.
This code works, just tried it on my machine. You must have bug on <img src="..." or <base href="" if you have one. Could you show us your html output so we can see what could be the problem?
You need to make sure that the image src is a valid URL to the script. Looking at the backslash in there my guess would be that that is in fact a filesystem path.

Categories