How to interpret a string for php code? - php

I have this:
this string might contain `<?php echo $var; ?>` php code
if it was in a file, it would be just an include / require command. But this time eval wont work. What to do?

The documentation of eval() says:
eval — Evaluate a string as PHP code
It also says below:
The code must not be wrapped in opening and closing PHP tags, ... It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags.
Put ?> in front of your string and it will become valid PHP code (empty code) followed by some text to be sent directly to the output and more fragments of PHP code properly enclosed in the PHP tags.

This will do what you want to be done:
$var = "Hello World!";
$string = 'this string might contain `<?php echo $var; ?>` php code';
//extract command
preg_match('/<\?php(.{1,}?)\?>/',$string,$match);
//print_r($match);
//execute command
eval($match[1]);

Related

How to not close string in PHP?

I have a bit of code that is in hundreds of my pages and I need to take it off. the problem is that it has <?php ?> tags, " and '.
What I was thinking to do was turn the bit of code in a string and use str_replace() once I fopened the file, but the ' and " are closing the string, making it impossible for me to do.
For example, it's something like this:
<?php $x = "test"; echo '1234;' ?>< ?php $y = 'testing' ?>
Is there a way to do stop it from closing strings? Or do you suggest any other solution?
PHP is not recursively embeddable or executable. Just because your files contain PHP code doesn't mean that php code magically special - inside the file, it's just text, like any OTHER text. You can search/replace as you want
$code = file_get_contents('somefile.php');
$fixed = str_replace('<?php blah blah blah ?>', '', $code);
file_put_contents('somefile.php', $fixed);
And note that that is literal PHP code inside the str_replace call - like I said, PHP is not recursively embeddable/executable. That's not really PHP code. It's a plain PHP string that happens to contain characters that end up LOOKING like php code.
e.g.
<?php
echo '<?php echo "foo"; ?>';
doesn't output just "foo". You get the literal characters ', <, ?, p, etc... as the output. That internal echo foo business is not PHP code in this context. It's a PHP string that contains characters that would be PHP code if it wasn't inside the ' quotes.
If you want to catch all the PHP tags in a file, you could loop through them, then run a preg_replace to pattern match the tags and remove them.
A quick example for regex could be http://regexr.com/3cu2t

Putting PHP code in a string

How do I put PHP Code into a string?
$phpCode = '<? if($condtion){ ?>';
For some reason, when I do this and echo out the code, I don't get the opening PHP tag, <?.
Am I missing something? Is there a better or more proper way to do this? I am currently looking at the PHP docs on strings but I would like to get your feedback.
Edit: The reason why I am using apsotrophes (') and not quotes (") is because I don't want the code to fill in the value for condition. I want it to echo as-is.
Use htmlspecialchars():
$phpCode = '<? if($condtion){ ?>';
echo htmlspecialchars($phpCode);
You need to echo htmlspecialchars($phpCode);
try these $str= htmlentities('<?php //***code***// ?>');
You can also use HTML entities.
When you replace just the opening square bracket in PHP, the rest will be considered a string when parsed with echo:
<?php
//< is the HTML entity for '<' (without quotes).
$str = '<?php yourstring ?>';
echo $str;
?>
Source HTML Entities
You can output PHP code as text in following way
$phpCode = '<? if($condtion){ ?>';
echo "<pre>";
echo htmlspecialchars($phpCode);
echo "</pre>";
There's already a few answers to this, but just to add my $0.02...
This code:
<?php
$test = '<?php echo "hello world!"; ?>';
echo $test;
?>
Produces a blank white screen in the browser, but if you view the source you'll see this output:
<?php echo "hello world!"; ?>
This has to do with the way the browser is rendering your PHP code. Browsers aren't meant to render PHP code, but rather HTML markup. If you're echoing out the code because you're testing what is going to be written to your file, then just view the source to validate what is being output is what you want to be written to the file. You won't see it in the browser itself because it doesn't know how to render the ?php tag, let alone what to do with the echo attribute.
Optionally, like everyone has stated already you can pass the string through htmlspecialchars if all you want to do is render it in the browser without having to view source. You wouldn't want to do that if you're writing it to the file, but may help you debug your output.
Another option would be to run your script from the command line. It won't attempt to render your output and instead just spit it out verbatim.
Eval php documentation
Use Eval() if you want to run the code in the string.
Example
$str = "Hello ";
eval('$str .= "World"');
echo $str;
/* Output: Hello World */

PHP Error in Browser

I am having trouble with this piece of code below. Whenever I run this file from browser it shows me the same code load_file($target_url); foreach($html->find(‘a’) as $link){ echo $link->href."
"; } ?> on the browser and not the desired result. I am working on a website using xampp. Php is also properly configured.
<?php
include_once('/simple.php');
$target_url = "http://www.example.com/";
$html = new simple_html_dom();
$html->load_file($target_url);
foreach($html->find(‘a’) as $link){
echo $link->href."<br />";
}
?>
For some reason it seems like the PHP parser interprets the -> in $html->load_file( as if it should close PHP parsing, thus showing you the rest of the code as HTML.
it interprets -> as if it was a ?>
The server is probably misconfigured, or some strange option is in effect.
Other PHP files may work fine if they do not contain -> so if not using objects
If they are allowed on your server, you could try alternative syntax:
<script language="php">
echo "This is HTML script tags.";
</script>
Or ASP style syntax
<%
echo 'This is ASP like style';
%>
Although ugly it might solve your problem
PHP or your server is not properly configured because instead of executing the code, it is simply outputting it to the browser.
The reason you only see the load_file() code onwards, is because the browser interprets the > on that line as a closing HTML tag. If you view->source in your browser, you'll see the full code.
The curly quotes! The curly quotes!
They show the file has been "treated" by the wrong program (Word???), so there is another char that gets modified usually by those nasty softwares, and it is the DASH (-)!
Your dash in $html->load is probably not a real dash "-" but some similar looking charachter like the long dash "—".
Look at the difference:
----------
real dashes -
––––––––––
alternate dash –
For some reason some parser (ftp?webserver?php?) gets confused by this unexpected char, and outputs a ? instead!
And this ? near the > gives a ?> that closes PHP!!!
Rewrite your file using a proper editor, just delete the dashes and write them again and it will work.

How do I display PHP code instead of displaying output?

I have a string variable which also has some PHP code in it. The code in the string var is getting run whenever I am displaying the string with echo. Is there anything (function) which can escape the meaning of PHP code while I use it with string?
Please help?
Using single quotes
echo 'foo is $foo';
will return foo is $foo
For more references: http://php.net/manual/en/function.echo.php
If you are already outputting the string, you might want to substitute echo for:
highlight_string — Syntax highlighting of a string
You can't execute PHP code by echo it to web browser by HTTP.
I mean you think about HTML, you can use htmlspecialchars to escape html code and print it without parse by browser like a HTML code.

PHP: how do you specify that you do not want a string evaluated?

I have some php code in a database like so
$x = "<?php some code here ?>";
but I want to output that whole line to the browser without php evaluating it. Right now it is evaluating it unfortunately. I thought about escaping it but that didn't work. How might a person accomplish this?
Thanks
EDIT:
<?php
echo '<? hey ?>';
echo "<dog dog>";
?>
if I run that code the dog dog tag shows up in the browser source code where as <? hey ?> does not. It seems like it would still be evaluating it.
Edit, got the answer, thanks everyone.
Just do:
echo htmlspecialchars($x);
'Single quotes' tell PHP to interpert the string exactly as is. It will include all whitespace and characters exactly as is.
"Double Quotes" tell PHP to parse the string. This reduces whitespace, replaces variables, and parses any other magic string things.
Finally, `backticks` are used for shell commands.
If you are trying to display it in a browser exactly like that, you might want to try htmlentities($string).
Do you want it to appear like that? If so, you'll need to use < and > (strictly only the < is necessary) to encode the string.
use '(single quotes) instead of "(double quotes)
Ih PHP double quotes evaluate expressions, single quotes do not so:
$a = 123;
$b = "value of $a"; // value of 123
$c = 'value of $a'; // value of $a
The only problem with single quotes is they don't understand characters like \n for newlines (that will be printed as \n not a newline when put in single quotes).
So is all you need:
echo '<?php some code here ?>';
?
For more information see Strings in the PHP manual.
You're a bit unclear about what gets evaluated.
If you're talking about variables, there are plenty of correct answers here.
If you're talking about the <? ?> block, something's wrong. That string should not be evaluated if within a PHP block (If you mean the opening and closing PHP statements).
Maybe you are missing the opening and closing <? ?> before and after your operation?
If you're outputting php code you might even consider using highlight_string which will perform syntax highlighting on the input

Categories