Replacing string with PHP code - php

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);

Related

htmlspecialchars and make links clickable

I have a PHP script which processes user input. I need to escape all special characters, but also make links clickable (turn them into <a> elements). What I need is:
function specialCharsAndLinks($text) {
// magic goes here
}
$inp = "http://web.page/index.php?a1=hi&a2=hello\n<script src=\"http://bad-website.com/exploit.js\"></script>";
$out = specialCharsAndLinks($inp);
echo $out;
The output should be (in HTML):
http://web.page/index.php?a1=hi&a2=hello
<script src="http://bad-website.com/exploit.js"></script>
Note that the amperstand in the link stays in the href attribute, but is converted to & in the actual content of the link.
When viewed in a browser:
http://web.page/index.php?a1=hi&a2=hello
<script src="http://bad-website.com/exploit.js"></script>
I eventually solved it with:
function process_text($text) {
$text = htmlspecialchars($text);
$url_regex = "/(?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+(?:\/\S*)?/";
$text = preg_replace_callback($url_regex, function($matches){
return ''.$matches[0]."";
}, $text);
return $text;
}
The first line html-encodes the input.
The second line defines the URL regex. Could be improved, but working for now.
The 3rd line uses preg_replace_callback, a function which is like preg_replace, but instead of supplying it with a replacement string, you supply a replacement function that returns the replacement string.
The 4th line is the actual function. It's quite self-documenting. htmlspecialchars_decode undoes the actions of htmlspecialchars (therefore making the link valid if it contained an amperstand).
Try this:
$urlEscaped = htmlspecialchars("http://web.page/index.php?a1=hi&a2=hello");
$aTag = 'Hello';
echo $aTag;
Your example doesn't work because if escaping whole html tag, a tag will never get processed by the browser, instead it will just display as plain text.
As you can see, stackoverflow escapes our whole input (questions/answers ...), so we can actually see the code, and not letting browser to process it.

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 */

How to utilize htmlspecialchars within echo

You can visit this link for an example of my promlem : http://jflaugher.mystudentsite.net/cmweb241/cmweb241_lab2.html
Everything is working correctly, except that I am having problems utilizing the htmlspecialchars in my echo. I am wanting the entity to show up in the echo and not the html character. I have tried placing the htmlspecialchars within the echo, but then the paragraph tags shows up. How do I utilize the htmlspecialchar in the echo, and display the echo in a paragraph tag? I have been at this for some time and have gotten no where, as I am very new to PHP.
For example, when I enter a '&', I get that echoed back. Instead of the '&', I want the entity &amp to be echoed.
<?php
$username = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['username']));
$password = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['password']));
$comment = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['comment']));
echo "<p> Your Username is: $username .</p> ";
echo " <p>Your Password is: $password . </p>";
echo " <p>Your Comment was: $comment . </p>";
?>
Say you enter &.
htmlspecialchars will turn this into &.
& is the HTML entity for &, so viewing the result in a browser displays &.
This is the normal purpose of htmlspecialchars, it preserves the visible character by escaping it for the medium (HTML) appropriately.
If you want & to turn into a visible &, the browser will need to receive &amp;. Apply htmlspecialchars twice to do that:
htmlspecialchars(htmlspecialchars($_POST['username']))
Maybe The Great Escapism (Or: What You Need To Know To Work With Text Within Text) helps you to understand the topic better.
I'm not sure what this means:
I am wanting the entity to show up in the echo and not the html character.
Are you saying that you want the entity to be displayed in your web page? htmlspecialchars is converting the characters to entities, but a browser will display those entities as the characters they represent.
If you want to actually see the entities in your browser, you can double-escape the values:
$username = htmlspecialchars(htmlspecialchars(str_replace(array("'", "\""), "",
$_POST['username'])));
But I don't really think that's the purpose of the exercise you're doing.
If you want to display the entities, you could apply htmlspecialchars() twice and it will turn all the & in & to &amp; and thus the entity itself will be displayed.
Another method is wrapping the output in <pre></pre> tags.
Try this approach:
<?php
$string = "<tag>&";
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
print $string;
It will print:
<tag>&
How to prevent XSS with HTML/PHP?

PHP Linefeeds (\n) Not Working

For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.
Example:
error_log('test\n', 3, 'error.log');
error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document
I'm pretty sure you are outputting to a html file.
The problem is html ignores newlines in source which means you have to replace the newlines with <br/> if you want a newline in the resulting page display.
You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');
to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);
It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.
Double quotes are what you want. Single quotes ignore the \ escape. Double quotes will also evaluate variable expressions for you.
Check this page in the php manual for more.
The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>
If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.

Categories