PHP code INCLUDE leaves a number when ECHOed through a $Value - php

This is an odd issue I ran into that adds a number (so far the number 1) to where the included data goes and positions the included data earlier in the code. I initially thought it might be some code on the TEXT.php that was causing the issue, but I simplified the two files until I got to a point where I have no idea what is causing the issue. The below code should result in the issue, despite how simple it is. While I can work around the issue, I would like to understand why I get a number and the included data moves.
The main code just references the Text.php in three ways.
First way is how I normally include php files.
Second is with some text before the echoed value that includes text, this results in a number appearing where the text should be and the text showing up earlier in the code.
Third is just the echoed value that includes text, this results in a number appearing where the text should be and no text.
All that exists on the Text.php is sample text.
Sample Text
Below is the main code.
<?php
$Value = include 'Text.php';
include 'Text.php';
echo "<br>";
echo "Example: " .$Value;
echo "<br>";
echo $Value;
?>
The main code results in the following when viewed on a browser;
Sample TextSample Text
Example: 1
1
Instead of:
Sample Text
Example: Sample Text
Sample Text
I would appreciate if someone that knows code better than I could explain why this happens this way. Thank you for your time.

The PHP manual page for include says:
Successful includes, unless overridden by the included file, return 1
So that explains where the 1 comes from.
For clarity: include executes the code in the included file. If that happens to involve an echo (or just some plain text outside a PHP block), then it echoes it, right there and then. That explains why you see "Sample Text" twice consecutively.
What include doesn't do is save the output and pass it back to the caller. If you want that then, in general, you should use a function with a return value, rather than an include.
N.B. You can use include with a file which has an inline return statement (see example #5 in the manual page), and it would work in the way you've tried above, capturing the return value. This is the scenario alluded to in the "unless overridden by the file" remark in the quotation above. But that's not what your current Text.php implementation is doing.

The $Value variable is what's returned by php's include function. As per php's documentation, this function returns 1.
Reference: https://www.php.net/manual/en/function.include.php
In the case of your code and output.
<?php
$Value = include 'Text.php'; // This line sets $Value to 1 as the include is successful.
include 'Text.php'; // This line echos the contents of Text.php
echo "<br>";
echo "Example: " .$Value; // Echos $Value, which is set to 1 on line 1
echo "<br>";
echo $Value; // Echos $Value again, which is set to 1 on line 1
?>
Sample TextSample Text <--- The text being included.
Example: 1 <--- The value of $Value is one, from a successful include
1 <--- The value of $Value, from a successful include

to get the output you want
Sample Text
Example: Sample Text
Sample Text
you should type
<?php
$Value = file_get_contents('Text.php');//to get 'Sample Text' in Text.php file
//include 'Text.php';#you don't need to include it, since you get the content of it.
echo $Value."<br>";//Sample Text
echo "Example: " .$Value;//Example: Sample Text
echo "<br>";//Line Break
echo $Value;//Sample Text
?>

Related

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

Insert variable and PDF tag into PHP code

This should be incredibly simple but i can't seem to figure it out.
I have the following code
<?php
$bookingid='12345';
include_once('phpToPDF.php') ;
//Code to generate PDF file from specified URL
phptopdf_url('https://google.com/','pdf/', $bookingid.pdf);
echo "<a href='pdf/$bookingid.pdf'>Download PDF</a>";
?>
It echo's correctly however when it comes to generate the pdf...
phptopdf_url('https://google.com/','pdf/', $bookingid.pdf);
...it misses out the fullstop so it generates 12345pdf whereas it should be 12345.pdf.
Again, i apologise for the probable simplicity of this but i can't seem to figure it out.
$bookingid.pdf
It tells php to concatenate variable $bookingid with constant pdf. Since constant pdf is undefined, it is casted to string and concatenated. Proper code will look like:
$bookingid . '.pdf'
or
"$bookingid.pdf"
This should be
$bookingid.".pdf"
PHP is seeing a string concatenation, concatenating pdf' to $booking. pdf is an undefined string, so PHP helpfully assumes that you mean the text itself, but it misses the full stop you also need.

PHP returning extra line returns

When posting from JS, PHP (5.3.8) returns some line returns in excess. For example:
if (isset($_POST['postId']) && $_POST['postId'] == "test") {
echo 'ok';
}
returns ok↵↵↵
Is this by design? How can I get rid of those line returns?
No, this is not by design. You have three newline output.
Try to delete the close tag of php ?>, if you don't have any html after php code.
Another way is just put exit; right after echo, you won't get newline again.
... right below your
echo 'ok';
paste another snippet:
echo '--------new line------';
if the gap (extra returns) show between your first echo and the -----new line----- it would be more than strange:) However if it shows below the ------new line----- you have probably some extra HTML text (tags) below your PHP statement.

How to print code generated by some function in php?

I have a code in my CMS that prints content:<?php print $content ?>
I would like to output the actual php and html code behind $content, ideally in the browser. What I mean here is not the result in the browser, but the actual code behind it.Is it possible at all?
EDIT: Just to explain further: I need to print the source code of $content. Basically this variable produce some html and php content. I would like to see the code it produces, change it and replace $content with my custom code. Ideally the source code should be printed in the browser, is there anny php function that does it?
First off install the Devel Module, it has a wonderful function called dpm() which will print the contents of any variable to the Drupal messages area.
Then you need to go into your theme's template.php file and implement hook_preprocess_page():
function mytheme_preprocess_page(&$vars) {
dpm($vars['content']);
}
That will print out the $content array before it's rendered into a string. In the same preprocess function you can also change $vars['content'] as you see fit, and the changes will be reflected in $content in page.tpl.php.
Hope that helps
What do you mean by 'the code'? I think what you want to do is not possible, unless you make some kind of quine it's not possible to output the actual php code of a php file when you run it.
If $content is something like:
$content = 3 + 4 + 5;
echo $content; will output 12 yes? But I'm taking it you want to output 3 + 4 + 5 or something along those lines. The thing is, PHP (although it doesn't feel like it) is compiled. In this trivial example, 3 + 4 + 5 is stored exactly nowhere in your compiled program, it is stored as 12 (since it's static). More complex lines of code will be stored as pointers, values etc., all in nicely obfuscated machine code. Getting back to the 3 + 4 + 5 requires reading the input file and outputting the relevant line, which is difficult (think about what happens if you add or remove some lines, or how your running program knows where in the source file it is, or even if it's in the right source file).
tl;dr: this is not possible.
Well, if you just want to see html source for $content, you should simply use htmlspecialchars :
echo htmlspecialchars($content);
http://php.net/htmlspecialchars
or http://php.net/htmlentities

PHP assign variable definition from a string

Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.
eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!
First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.

Categories