Get generated html content of php script on same server - php

I have a php page that outputs html to the browser based on a query string that is parsed. The issue I am having is that I need to retrieve this html source code dynamically via php.
The following code will not work because it tries to resolve an absolute path as it's on the same server:
$url = 'http://example.com/myScript.php';
$html = file_get_contents($url);
If I manually set the absolute path it just returns the php contents as text (not executed like a browser would do):
$url = '/dir1/dir2/dir3/dir4/myScript.php';
$html = file_get_contents($url);
I then researched it and found that using ob_get_contents could work. The code below works as expected, executing the script and returning the html output.
$url = '/dir1/dir2/dir3/dir4/myScript.php';
ob_start();
include($url);
$html = ob_get_contents();
ob_end_clean();
The problem with the above solution is that as soon as I put the query string on the end it fails. I think this is because it's treating the query string as part of the file name.

Use PHPs ob_get_contents
<?php
ob_start();
$original_get = $_GET;
$_GET = ["query" => "tags", "you" => "need", "in" => "file.php"];
$file = "file.php";
include($file);
$_GET = $original_get;
$content = ob_get_contents();
ob_clean();
echo $content;

Related

phpqrcode library return image as a string

http://sourceforge.net/projects/phpqrcode/, is a great library but i can't find how to return the png image as a string, the basic examples are
QRcode::png('code data text', 'filename.png'); // creates file
QRcode::png('some othertext 1234'); // creates code image and outputs it directly into browser
i checked the documentation and nothing, help! :B
ob_start();
QRCode::png('text', null);
$imageString = base64_encode( ob_get_contents() );
ob_end_clean();
$qrTempDir = 'path/to/your/temp';
$filePath = $qrTempDir.'/'.uniqid();
QRcode::png('some text', $filePath);
$qrImage = file_get_contents($filePath);
unlink($filePath);
This should be what you're looking for. You can extend it to show an image like that:
<img src="data:image/png;base64,<?php echo base64_encode($qrImage) ?>" />
Unfortunately, the library does not support any other method at the moment, because calling the QRcode::png function without the file parameter not only makes it send those headers, but it also exits the code execution, so there is no retracting or overwriting the headers.
I ran into the same problem as #iim.hlk
This is what i did slightly modified #Lusitanian his answer to this
ob_start();
QRCode::png($string);
$imageString = base64_encode( ob_get_clean() );
header('Content-Type: text/html');
This fixes the header issue by simply overwriting it. Not clean or anything but it works for the purpose.
this works for me
include '../phpqrcode/qrlib.php';
$content = "any content";
ob_start();
QRcode::png($content);
$result_qr_content_in_png = ob_get_contents();
ob_end_clean();
// PHPQRCode change the content-type into image/png... we change it again into html
header("Content-type: text/html");
$result_qr_content_in_base64 = base64_encode($result_qr_content_in_png);
then in your html file
<img src="data:image/jpeg;base64,$result_qr_content_in_base64'"/>

How to get include contents as a string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Execute a PHP file, and return the result as a string
PHP capture print/require output in variable
I am trying to get the contents of an include to a string. Is that possible?
For example, if I have a test.php file:
echo 'a is equal to '.$a;
I need a function, say include_to_string to include the test.php and return what would be output by in in a string.
Something like:
$a = 4;
$string = include_to_string(test.php); // $string = "a is equal to 4"
ob_start();
include 'test.php';
$string = ob_get_clean();
I think is what you want. See output buffering.
ob_start();
include($file);
$contents = ob_get_contents(); // data is now in here
ob_end_clean();
You can do this with output buffering:
function include2string($file) {
ob_start();
include($file);
return ob_get_clean();
}
#DaveRandom points out (correctly) that the issue with wrapping this in a function is that your script ($file) will not have access to variable defined globally. That might not be an issue for many scripts included dynamically, but if it is an issue for you then this technique can be used (as others have shown) outside of a function wrapper.
** Importing variables
One thing you can do is to add a set of data you would like to expose to your script as variables. Think of it like passing data to a template.
function include2string($file, array $vars = array()) {
extract($vars);
ob_start();
include($file);
return ob_get_clean();
}
You would call it this way:
include2string('foo.php', array('key' => 'value', 'varibleName' => $variableName));
and now $key and $variableName would be visible inside your foo.php file.
You could also provide a list of global variables to "import" for your script if that seems clearer to you.
function include2string($file, array $import = array()) {
extract(array_intersect_key($GLOBALS, array_fill_keys($import, 1)));
ob_start();
include($file);
return ob_get_clean();
}
And you would call it, providing a list of the globals you would like exposed to the script:
$foo='bar';
$boo='far';
include2string('foo.php', array('foo'));
foo.php should be able to see foo, but not boo.
You could also use this below but I recommend the above answer.
// How 1th
$File = 'filepath';
$Content = file_get_contents($File);
echo $Content;
// How 2th
function FileGetContents($File){
if(!file_exists($File)){
return null;
}
$Content = file_get_contents($File);
return $Content;
}
$FileContent = FileGetContents('filepath');
echo $FileContent;
Function in PHP manual : file_get_contents

Get parsed PHP file

I'm trying to get the contents of a PHP file after it is parsed, and then store it in a variable.
I couldn't get any useful information via Google, except for this one example:
ob_start();
include $file;
$content = ob_get_clean();
But this returns the contents as plain text, i.e.: The <?php and ?> tags are still there, and all code between the tags isn't parsed.
So I wanted to know, how can I do this properly?
update:
This is content of the file which is being included:
Testcontent
<?php echo 'This should be parsed, right?'; ?>
I was using this function several years ago for a sort of a template engine, it seems to do what you need - pass a string with some PHP code inside and it will return it with PHP executed. Surprisingly, it still works :-)
function process_php( $str )
{
$php_start = 0;
$tag = '<?php';
$endtag = '?>';
while(is_long($php_start = strpos($str, $tag, $php_start)))
{
$start_pos = $php_start + strlen($tag);
$end_pos = strpos($str, $endtag, $start_pos); //the 3rd param is to start searching from the starting tag - not to mix the ending tag of the 1st block if we want for the 2nd
if (!$end_pos) { echo "template: php code has no ending tag!", exit; }
$php_end = $end_pos + strlen($endtag);
$php_code = substr($str, $start_pos, $end_pos - $start_pos);
if( strtolower(substr($php_code, 0, 3)) == 'php' )
$php_code = substr($php_code, 3);
// before php code
$part1 = substr($str, 0, $php_start);
// here set the php output
ob_start();
eval($php_code);
$output = ob_get_contents();
ob_end_clean();
// after php code
$part2 = substr($str, $php_end, strlen($str));
$str = $part1 . $output . $part2;
}
return $str;
}
Based on Tyil's last comment he wants to entirety of the php file within a variable:
Tyil, what if my include file looks like this: <?php echo 'test stuff'; $foo = 'one';. What does $content contain and what happens if I try to access $foo from the including file?
#MikeB $content contains the string <?php echo 'test stuff'; $foo = 'one';. var_dump($foo); in the including file returns NULL.
<?php
$file = 'include.php';
$content = file_get_contents($file);
var_dump($content); // (string) "<?php echo 'This should be parsed, right?'; $foo = 'one'; ?>"
include.php:
<?php echo 'This should be parsed, right?'; $foo = 'one'; ?>
If you can modify your $file, than use return in it.
Otherwise cURL it (opens a web page like browser does).
This should definitely work. And it does for me:
[ghoti#pc ~/tmp]$ cat file1.php
#!/usr/local/bin/php
<?php
$file="file2.php";
include($file);
[ghoti#pc ~/tmp]$ cat file2.php
<?php echo "This should be parsed, right?\n"; ?>
[ghoti#pc ~/tmp]$ ./file1.php
This should be parsed, right?
[ghoti#pc ~/tmp]$
You might want to look at your included file (named in $file) and see if there is perhaps some strange character after the initial <?php that might cause it not to be interpreted as a PHP script.
To see a hex dump of what's in the file (so you can see what character actually follows <?php rather than what's displayed in your editor), use: od -c filename.php | less.
To do this, you have to use cURL.
Well, if you want to do it effectively, anyhow.
I know I'm several years late, but I was also looking for a solution to this issue, and I'd like to share the solution. Keep in mind, while this script does indeed get a PHP HTML page parsed, downloading via the web protocol is very slow, at least in my tests.
function GetHTMLPage($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
...don't thank me. Thank David Walsh. (https://davidwalsh.name/curl-download)

PHP - print content from file after manipulation

I'm struggling trying to read a php file inside a php and do some manipulation..after that have the content as a string, but when I try to output that with echo or print all the php tags are literally included on the file.
so here is my code:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
$file = file_get_contents($path);
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
and this will return a string like
<div id="content>
<h2>Here is my title</h2>
<p><? echo "my body text"; ?></p>
</div>
but this will print exactly the content above not compiling the php on it.
So, how can I render this "compilePage" making sure it returns a compiled php result and not just a plain text?
Thanks in advance
function compilePage($page, $path) {
$contents = getMenuFor($page);
ob_start();
include $path;
$contents .= "\n".ob_get_clean();
return $contents;
}
To evaluate PHP code in a string you use the eval function, but this comes highly unadvised. If you have a file containing PHP code, you can evaluate it with include, include_once, require, or require_once depending on your need. To capture the output of an included file - or required, or whichever method - you need to enable output buffering.
You can use output buffering for this, and include the file normally:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
ob_start();
include $path;
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
The include() call will include the PHP file normally, and <?php blocks will be parsed and executed. Any output will be captured by the buffer created with ob_start(), and you can get it later with the other ob_* functions.
You need to use include() so it will execute. You can couple this with output buffering to get the return in a string.
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
//output buffer
ob_start();
include($path);
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}

file_get_contents with query string

i am trying to send email from php
i have one php file with all values & other php template file.
(both files are on same server)
i am using file_get_contents to get contents of php template file for example
$url="emil_form.php";
$a="uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}
...... EMAIL Sending Code ..........
and here is code for emil_form.php (email template file)
Your Name is : <?php $_GET['uname']; ?>
so once i got data in $Content i can send it by email.
but i am getting error unable to open file....
what i want is pass data from original php file to template php file and what will be output of template stored in variable so i can send it by email.
how can do this ?
Thanks
The real problem would be that you try to read a local file with a http query string behind it. The file system don't understand this and looks for a file called "emil_form.php?uname=uname".
$_GET / $_POST / etc only works over a http connection.
Try to put a placeholder like "%%NAME%%" in your template and replace this after reading the template.
<?php
$url = "emil_form.php";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}
$Content = str_replace('%%NAME%%', $a, $Content);
// sending mail....
Template will look like this:
Your Name is: %%NAME%%
Here's an alternative solution...
Use the relative path or absolute path as suggested by "cballou" to read file.
But insted of wirting a php file use a simple text file put you message template in it replace <?php $_GET['uname']; ?> with something unique like %uname% (replacement keys).
Read the file content into a variable and replace the replacement keys with your variable like so,
$url = "/usr/local/path/to/email_form.txt";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}else{
$content = str_replace('%uname%', $a, $content);
}
$url = sprintf("%s://%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME']);
$content = file_get_contents($url."/file.php?test=".$test);
echo $content;
Please note that you had a filename error in $url which wss trying to load emil_form.php.
A secondary issue seems to be the path you are using for your call to $url. Try making it an full URL in order to properly parse the file, avoiding any templating you may otherwise have to do. The RTT would be slower but you wouldnt have to change any code. This would look like:
$url = 'http://www.mysite.com/email_form.php';
$a = "uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}

Categories