Setting $variable's content using include() - php

I'm trying to send out a voucher, via the PHP's email() function, where I reference an external .php file using include() as the message contents. Heres the code:
$message = '<?php include ("/fullpath/inc/voucher.php"); ?>';
This isn't working because I'm declaring it as a text string, but if I don't it will just print out the contents and not put it as the content of the variable. Any ideas?

You can use the ob_buffer for that, try this:
<?php
ob_start(); // start buffer
include("file.php"); // read in buffer
$var=ob_get_contents(); // get buffer content
ob_end_clean(); // delete buffer content
echo $var; // use $var
?>
Example from http://www.webmaster-eye.de/include-in-Variable-umleiten.210.artikel.html (German)

In this post two solutions depending on the circumstances will be described..
voucher.php is returning a value
If voucher.php has a return statement in it you can safely use include to get a hold of this returned value.
See the below example:
voucher.php
<?php
$contents = "hello world!";
...
return $contents;
?>
...
$message = include ("/fullpath/inc/voucher.php");
voucher.php is printing data that I'd like to store in a variable
If voucher.php is printing data that you'd like to store in a variable you can use php's output buffering functions to store away the printed data and then assign it to $message.
ob_start ();
include ("/fullpath/inc/voucher.php");
$message = ob_get_contents ();
ob_end ();

ob_start();
include ("/fullpath/inc/voucher.php");
$message = ob_get_clean();
However output buffering in most cases is considered as bad practice and not recommended to use
Like in your case you better have a function declared in voucher.php that returns the message as a string. So all the code could be as simple as: $message = get_voucher();

I've encountered the same ploblem, here is the functions that resolves the problem for me. It uses the Tobiask answer
function call_plugin($target_) { // $target_ is the path to the .PHP file
ob_start(); // start buffer
include($target_); // read in buffer
$get_content = ob_get_contents(); // get buffer content
ob_end_clean();
return $get_content;
}

You want to use the readfile() function instead of include.
See: http://en.php.net/manual/en/function.readfile.php
If you want to get the =results= of PHP parsing the voucher.php one way is to make sure that you put voucher.php on a reachable URL, and then call it like:
$message = file_get_contents("http://host.domain.com/blabla/voucher.php");
This would insert the contents/output of the parsed voucher.php into the variable $message.
If you can't reach the voucher.php publically you have to rewrite it to output the string in the end with the return() function, or write a function in voucher.php that outputs the string you want when called after which you include() it and call the function from within this master PHP script.

$message = include '/fullpath/inc/voucher.php';
and withing /fullpath/inc/voucher.php
// create $string;
return $string;

$message=file_get_contents("/fullpath/inc/voucher.php");

Related

PHP: Can You Pass Include Through a Function?

Is it at all possible to include a file through a function? I don't mean returning the contents as a string. I'd like to create my own custom include method, but right now it doesn't seem possible.
For instance, PHP's include method outputs file contents. I'd like to output file contents, but run them through another function first.
For example:
function include_filter($file){
include($file);
}
include_filter($file);
This example does not use additional functionality, because my primary question here is how to include through a function at all. You can see the issue.
If I include through a function such as include_filter, the code will be included locally inside the function only, not at the line the function was called (line 4 in the example).
The include statement does not output the file contents. However, it does evaluate the file you're including, so if that file contains any echo statements then yes, those are executed the moment you include that file.
You can use an output buffer to catch that output and do something with it before re-echo'ing it:
included_file.php:
<?php
echo "This came from an included file.";
main_file.php:
<?php
function include_filter($path) {
ob_start();
include $path;
$output = ob_get_contents();
ob_end_clean();
echo str_replace("an included file", "a filter function", $output);
}
include_filter("included_file.php");
// will output "This came from a filter function."
Demo: https://3v4l.org/2XkL7

Return html response from PHP page in to variable

I am trying to generate an email with some HTML that is created via another PHP file.
Email generating file is run by a cron running every hour.
Another file exists that generates the HTML required for the email.
The HTML generating file does not have a function that I can call, for instance:
$emailBody = generateHTML($id);
The HTML generating file was designed to be included on a page that you wished to display the HTML, for instance:
include "htmlGenerator.php";
My question is: How can I get what the htmlgenerator.php file returns in to a variable, ready to be pushed in to an email.
Apologies if this is not very clear, I will be happy to answer any questions.
Thanks in advance!
If I understood what you said, you can use output buffering,
so that you can get the output of htmlGenerator.php
For example:
ob_start();
// as an example
echo "Hello World";
// or in our case
include "htmlGenerator.php";
$result = ob_get_contents();
ob_end_clean();
You can also create a simple function like this:
function include_output($filename)
{
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
$mycontent = include_output("htmlGenerator.php");
Read the php documentation for further details.
Check out the built-in functions ob_start and ob_get_clean.
You can then do something like:
ob_start();
include( "file.php");
$var = ob_get_clean();

How to assign the contents of a file to a variable in PHP

I have a document file containing HTML markup. I want to assign the contents of the entire file to a PHP variable.
I have this line of code:
$body = include('email_template.php');
When I do a var_dump() I get string(1) "'"
Is it possible to assign the contents of a file to a variable?
[Note: the reason for doing this is that I want to separate the body segment of a mail message from the mailer script -- sort of like a template so the user just modifies the HTML markup and does not need to be concerned with my mailer script. So I am including the file as the entire body segment on mail($to, $subject, $body, $headers, $return_path);
Thanks.
If there is PHP code that needs to be executed, you do indeed need to use include. However, include will not return the output from the file; it will be emitted to the browser. You need to use a PHP feature called output buffering: this captures all the output sent by a script. You can then access and use this data:
ob_start(); // start capturing output
include('email_template.php'); // execute the file
$content = ob_get_contents(); // get the contents from the buffer
ob_end_clean(); // stop buffering and discard contents
You should be using file_get_contents():
$body1 = file_get_contents('email_template.php');
include is including and executing email_template.php in your current file, and storing the return value of include() to $body1.
If you need to execute PHP code inside the of file, you can make use of output control:
ob_start();
include 'email_template.php';
$body1 = ob_get_clean();
file_get_contents()
$file = file_get_contents('email_template.php');
Or, if you're insane:
ob_start();
include('email_template.php');
$file = ob_end_flush();
As others have posted, use file_get_contents if that file doesn't need to be executed in any way.
Alternatively you can make your include return the output with the return statement.
If your include does processing and outputs with echo [ed: or leaving PHP parsing mode] statements you can also buffer the output.
ob_start();
include('email_template.php');
$body1 = ob_get_clean();
TimCooper beat me to it. :P
Try using PHP's file_get_contents() function.
See more here: http://php.net/manual/en/function.file-get-contents.php
Yes you can its easy.
In the file you want to use the variable place this
require_once ‘/myfile.php';
if(isset($responseBody)) {
echo $responseBody;
unset($responseBody);
}
In the file you are calling /myfile.php place this
$responseBody = 'Hello world, I am a genius';
Thanks
Daniel
You have two optional choices
[Option 1]
Create a file called 'email_template.php'
inside the file add a variable like so
$body = '<html>email content here</html>';
in another file require_once 'email_template.php'
then echo $body;
[Option 2]
$body = require_once 'email_template.php';

Php ob_get_contents() returns empty string if the included file during buffering is not small

Let's say i have a file consisting of 5 lines of text and every line has 50 chars. The output buffer contents are returned correctly but if I have a file containing 100 lines of text the output buffer returns empty string (string with value null).
I do it like so:
ob_start();
include "file.php"
$string = ob_get_contents();
ob_end_clean();
OR
$string = $this->load->view('view', $data, true);
Im doing this inside codeigniter if that makes any difference.
I tried to load the file with Code igniter's load->view function with third parameter set to true the result is the same. Tried also giving ob_start() a big number -> ob_start(9999999); same result;
I'd propose to use ob_get_flush to ensure, that nothing is still kept in some internal buffer..
Quite unlikely, but what does this instead of your code print?
require_once( "file.php" );
Just to ensure, that the stuff in file.php isn't surrounded by <?php /** **/ php?>.
And what does
echo ob_get_level();
output just before your code? Shouldn't be relevant, if other outbut-buffering is already enabled, but...
Why are you using ob functions to get the contents of a file? Why not file_get_contents?
you have just to add some lines in index.php (the root of CodeIgniter)
ob_start();
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*------------
+
require_once BASEPATH.'core/CodeIgniter.php';
$data = ob_get_contents();
ob_clean();
echo $data; /// or anything else
that's all !

Streaming output to a file and the browser

So, I'm looking for something more efficient than this:
<?php
ob_start();
include 'test.php';
$content = ob_get_contents();
file_put_contents('test.html', $content);
echo $content;
?>
The problems with the above:
Client doesn't receive anything until the entire page is rendered
File might be enormous, so I'd rather not have the whole thing in memory
Any suggestions?
Interesting problem; don't think I've tried to solve this before.
I'm thinking you'll need to have a second request going from your front-facing PHP script to your server. This could be a simple call to http://localhost/test.php. If you use fopen-wrappers, you could use fread() to pull the output of test.php as it is rendered, and after each chunk is received, output it to the screen and append it to your test.html file.
Here's how that might look (untested!):
<?php
$remote_fp = fopen("http://localhost/test.php", "r");
$local_fp = fopen("test.html", "w");
while ($buf = fread($remote_fp, 1024)) {
echo $buf;
fwrite($local_fp, $buf);
}
fclose($remote_fp);
fclose($local_fp);
?>
A better way to do this is to use the first two parameters accepted by ob_start: output_callback and chunk_size. The former specifies a callback to handle output as it's buffered, and the latter specifies the size of the chunks of output to handle.
Here's an example:
$output_file = fopen('test.html', 'w');
if ($output_file === false) {
// Handle error
}
$write_ob_to_file = function($buffer) use ($output_file) {
fwrite($output_file, $buffer);
// Output string as-is
return false;
};
ob_start($write_ob_to_file, 4096);
include 'test.php';
ob_end_flush();
fclose($output_file);
In this example, the output buffer will be flushed (sent) for every 4096 bytes of output (and once more at the end by the ob_end_flush call). Each time the buffer is flushed, the callback $write_ob_to_file will be called and passed the latest chunk. This gets written to test.html. The callback then returns false, meaning "output this chunk as is". If you wanted to only write the output to file and not to PHP's output stream, you could return an empty string instead.
Pix0r's answer is what you want unless you actually need it "included" rather than just executed. For example, if you have login information before the test.php, it will not get passed into the file if you call it with fopen.
If you need it genuinely included, then what you have is the simplest method, but if you want constant output, you'll need to actually write test.php in a manner that outputs as well as stores the information as it goes. As far as I know there's no way to both collect buffer and output it as you go.
Here you go x-send-file, use mod_xsendfile to send file efficiently, really easy.

Categories