How to not close string in PHP? - 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

Related

file_get_contents returns an incorrect result if the content contains a sign "<" and a symbol after it [duplicate]

I have a string in my code as per the following example:
<?php
$find = '<tag';
$string = 'blah blah <tag=something>';
?>
Simple enough, but when I try to echo the strings, it's not liking the < or > characters. All that get's echo'ed is:
blah blah
So, basically i'm guessing I need to escape these characters to get them to work in PHP but im not sure exactly how. I'm using this for a templating system, so in the html file a file can be included by using:
<include="filename.html">
So I don't need to show the < and > characters on the screen at any time, I just need to read the file, find the instances of these tags and do some magic. I've got all of that part working but It's just any string that contains more than / less than operators that don't seem to work OK.
Any ideas?
With PHP you can generate HTML markup, so you have to find a way to distinguish between HTML element characters ( < & > ). There exist special sequence of characters in HTML that are called HTML entities. Those are described with an ampersand, some sort of shorthand and end with a semi-colon.
Here are some examples:
> : > (greater-than)
< : < (less-than)
& : & (ampersand)
» : » (right angle quote marks)
é : é (e acute)
Almost all characters can be represented with such entities, but it quickly gets tedious. You only have to remember the < and > ones, plus the & for URLs.
Your code should be rewritten like this if your intention was to show the less-than / greater-than signs.
<?php
$find = '<tag';
$string = 'blah blah <tag=something>';
?>
As mentioned in other answers, you can use the function htmlspecialchars() to convert characters in a variable (e.g. from user input).
<?php echo htmlspecialchars($string); ?>
will display blah blah <tag=something> for viewing in a web browser. Else, if you were using PHP on the command line for example, you would not need to use this function.
You need to use HTML characters to avoid it being turned into HTML.
so:
echo htmlspecialchars("<hello>");
Use htmlspecialchars()
echo htmlspecialchars('string you want to echo');
you can use the htmlspecialchars function to escape the < brackets..

Replacing string with PHP code

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

How do I turn my query result into a link?

I am returning data from three columns and displayed it with:
echo "<p><h3><span class='tyler'>".$results['COL 2']."</span></h3>".$results['COL 4'].$results['COL 3']."</p>";
This works fine. COL 4 is an actual URL and I am trying to put it in an anchor tag with COL 3 as the anchor text:
echo "<p><h3><span class='tyler'>".$results['COL 2']."</span></h3>""<a href=".$results['COL 4']"/>".$results['COL 3']."</a></p>";
I am trying to use this code but it doesn't work. My assumption is that the problem has something to do with the back to back quotes after the closing h3 tag. How would I go about making this work?
It can get confusing to build large strings that are output to HTML. This is what you have:
echo "<p><h3><span class='tyler'>"
.$results['COL 2']
."</span></h3>""<a href=".$results['COL 4']"/>"
.$results['COL 3']
."</a></p>";
I've broken it up to more clearly reference what is going on. In the third line (starting with the close-span tag), you have two double quotes right next to each other. Further on, you have quotes opening the close-slash part of the tag, but not a string concatenation operator (.). Finally, you are confusing double and single quotes. You want:
."</span></h3><a href='".$results['COL 4']."'/>"
But a better way of doing this would be to split out your components:
$title = $results['COL 2'];
$href = $results['COL 4'];
$anchor_text = $results['COL 4'];
// Here you can add debugging statements to ensure you have the right values.
$paragraph = "<p><h3><span class='tyler'>%s</span></h3><a href='%s'>%s</a></p>"
echo sprintf($paragraph, $title, $href, $anchor_text);
This method uses sprintf to 'slot in' the strings you want. It allows you to be more clear about building the html, without worrying about what the specific 'dynamic' values are. There are, of course, many other ways of doing this sort of 'templating'.
An Aside on String Building in PHP
This line of code assigns a simple string to a variable in PHP:
$message = "Hello world!";
This line of code 'concatenates' three strings using the concatenation operator (which is a dot: .):
$html = "<p>".$html."</p>";
This line would yield an equivalent result:
$html = "<p>Hello world!</p>";
This line will yield an error:
$bad = "<p>""Hello world!""</p>";
The reason it yields an error is because the language will 'tokenize' the code into something like:
<variable name> <assign> <string> <string> <string> <end statement>
Except that, semantically, three <string>s in a row doesn't make sense. It needs an 'operator' between them, like so:
<variable name> <assign> <string> <concatenate> <string> <concatenate> <string> <end statement>
PHP knows how to 'parse' this string of tokens. It will know to evaluate each string, and then concatenate them together. An intermediate stage becomes this:
<variable name> <assign> <string (composed of three previous strings)> <end statement>
It knows this because the concatenation operator tells it how to combine those strings.
That brings us back to using the dot/concatenation operator:
$html = "<p>Hello world!</p>";
Now, HTML markup looks like this:
SO Help Page
And when PHP 'outputs' the final result, all it is doing is 'echo'ing or 'printing' a string to the HTML response. Given that, and given that PHP interprets a double quote as the 'end' of a string, how do you put strings into a variable, so it prints out like the HTML above? This won't work, because PHP doesn't know how to interpret http://... in this context:
echo "SO Help Page";
There are a few ways to get around this. You can 'escape' the double quotes:
echo "SO Help Page";
By inserting a \ in the string before the double quote you signal to PHP to not end the string token, and to therefore parse the whole thing as a single string.
Alternatively, HTML also accepts single quotes for it's attribute values. So you can do this:
echo "<a href='http://www.stackoverflow.com/help'>SO Help Page</a>";
Which yields this on the HTML response:
<a href='http://www.stackoverflow.com/help'>SO Help Page</a>
Regardless of which way you go, you have to remember that the PHP code does not magically know that you're building an HTML page: it is simply constructing and printing strings to the HTML response. You have to tell it when to ignore parts of the string.
My point above is that for long enough PHP scripts, this can become confusing. So breaking down the strings into manageable chunks, so you can see what you're inserting and where things (like quotes, open and close tags, etc.) are makes your life easier.

PHP string cut short

Why does this code
$string = "!##$%^&*(<a#g.com";
echo $string;
only output:
!##$%^&*(
Is this is a PHP bug?
Because < is a reserved character in in HTML :)
Use < and >
Read this for more information
http://www.w3schools.com/HTML/html_entities.asp
You can use the function htmlspecialchars to convert such special chars
http://php.net/manual/en/function.htmlspecialchars.php
I'm not seeing that:
http://ideone.com/zhycx
Perhaps you've got some weird characters in your file? Make sure you're using a "normal" encoding on your source code, as well.
You need to do:
echo htmlentities($string);
to display the string as it is on a browser. This is because the < in the string is interpreted by the browser as start of a HTML tag.
So it's not PHP but the browser that is causing this behavior. If you do the exact same display on a command line, you'll see all the characters.
If you are viewing the output in a web browser, then the < begins a tag and is usually not displayed but interpreted in the HTML document structure parser. Also, a $ inside of a double-quoted string is interpolated as the variable name that follows it; try using single quotes where this won't happen.
Try this:
$string = '!##$%^&*(<a#g.com';
echo htmlentities($string);

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