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 */
Related
hello every body i had a problem with echo in php that might be very simple but i'm a bit new in php.
i had a code like this:
<?php echo '<script>var str=Array(1);str.push('.$user_id.')</script>';?>
in this code i want to display script text instead of calling java script. what shall i do?
i have already tried every kind of writing types such as single quotes and double quotes like below
<?php echo '"<script>"var str=Array(1);str.push('.$user_id.')"</script>"';?>
even tried \ at the beginning and end of script but none of them worked.
You need to use htmlspecialchars() function to escape html tags.
<?php echo htmlspecialchars('<script>var str=Array(1);str.push('.$user_id.')</script>');?>
I am trying to replace a certain string with some PHP code using the str_replace function. I want to replace "[GOOGLE]" with <?php echo "hello"; ?>
Here's what I have so far:
$text = str_replace("[GOOGLE]", "<?php echo 'hello'; ?>", $text);
When running this code, it does replace [GOOGLE], but the replacement is not shown in the browser. When I go to see the page's source code, the replacement is: <?php echo 'hello'; ?> you can see the PHP tag for some reason. However, nothing is displayed on the page. How do I correct this problem so that [GOOGLE] is replaced with hello? Note: I do not want to replace my PHP code in the str_replace function with the actual "hello" string, I want to do this with PHP code. For now, I am trying to go with something simple. My goal is to replace [GOOGLE] with an if/else statement and Ad code for my CMS.
Your echo appears misplaced. It seems to me you want to output the result of replacing "[GOOGLE]" with "hello", in which case (1) perform the replacement then (2) echo the result. Perhaps:
$text = str_replace("[GOOGLE]", "hello", $text);
echo $text;
The reason you don't see it in the browser is that replacement, <?php echo 'hello'; > is within angled brackets. Angled brackets are special to HTML, in that they denote an operation the browser is to perform. For example, <b> means "start bolding text". When the browser sees "<?php ... ?>" it considers that a tag. It doesn't know what to do with the tag, so nothing appears rendered. However, it does remain in source as that text is, indeed, part of the source.
If you literaly want to see "<?php echo 'hello'; ?>" then you need to escape the angled brackets:
$text = str_replace("[GOOGLE]", "<?php echo 'hello'; ?>", $text);
Here the angled brackets have been replaced with their escaped versions: "<" becomes "<" and ">" becomes ">". Of course, you might tire of doing this manually. In which case, consider using htmlspecialchars().
I guess you want to display php code on html page.
You need to use htmlspecialchars() for that because this string will be partly interpreted as html tag.
In your example it would be:
$text = str_replace("[GOOGLE]", "<?php echo 'hello'; ?>", $text);
// later when producing html...
echo htmlspecialchars($text, ENT_QUOTES); //default encoding is UTF-8
WARNING: It's mandatory to do it with every user supplied content btw, because javascript could be also interpreted and someone could do nasty things with it (XSS)
I'm starting off with something simple for right now to learn how to do it. I want to really replace [GOOGLE] with Adsense code to use in my CMS
Don't do it this way.
Put your Adsense code in an include or a variable or something, and do:
$text = str_replace("[GOOGLE]", file_get_contents('google-analytics.html'), $text);
or:
$googleAnalytics = '<script> the code Google gives you </script>';
$text = str_replace("[GOOGLE]", $googleAnalytics, $text);
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]);
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.
I currently am trying to echo the contents of a text file within JavaScript. Everything works but there is a problem. The text within the text contains apostrophes, which is throwing everything off. Below is a portion of the code that I am using. I am using this code for MANY text files. I have considered changing each apostrophe to "\'" in each text file, but there are a lot of text files to deal with. I was just curious if there was another way to work around this. Any ideas are greatly appreciated.
<?php
$lyrics = file_get_contents('Includes/Songs/Lose_My_Mind.txt');
?>
JavaScript snippet:
var scrollercontent='<?php echo $lyrics; ?>'
Whilst addslashes will mostly work, this is better:
var scrollercontent= <?php echo json_encode($lyrics, JSON_HEX_TAG); ?>;
json_encode works for any datatype, not just strings. For strings it adds the quotes at the sides for you, and it will work for any character including control codes such as the newline character.
The JSON_HEXs are a PHP 5.3 feature. HEX_TAG replaces < with a JavaScript string literal encoding like \x3C, which means you can put any string literal in a <script> block without worrying that it might contain a </script> sequence that would prematurely end the script block. (Even just </ on its own is technically invalid.)
Try to use addslashes() function. In your case:
var scrollercontent='<?php echo addslashes($lyrics); ?>'
Try
addslashes(nl2br($lyrics))
(nl2br replaces new lines with <br> tags.)
Try changing this
var scrollercontent='<?php echo $lyrics; ?>'
to this
var scrollercontent='<?php echo addslashes($lyrics); ?>'
or
var scrollercontent='<?php echo htmlentities($lyrics); ?>'
these should help escape or entitize quotes etc...
Have you tried:
<?php $lyrics = addslashes(file_get_contents('Includes/Songs/Lose_My_Mind.txt')); ?>
You could add the following line after your file_get_contents command:
$lyrics = str_replace("\'","\\'",$lyrics);
This will change all of the single apostrophes to escaped apostrophes and should play nice with Javascript.
<?php
$lyrics = nl2br(htmlentities(file_get_contents('Includes/Songs/Lose_My_Mind.txt'), ENT_QUOTES));
?>
var scrollercontent="<?php echo $lyrics; ?>";