echo over several lines, escape variables? - php

I want to do output like this:
echo <<<END
$monkey
END;
where the output would be '$monkey' (i.e. all text up to END is treated as normal text, and not parsed)
I want to avoid escaping or modify any of the text up until the END.
is that possible?
e.g. ideally I want to do something like this
echo '
loads of lines here
';

In PHP 5.3, you can use nowdoc:
$var = <<<'END'
$monkey
END;
Otherwise, you'll always to worry about escaping something (all the escape codes and the dollar sign on heredoc, the same plus double quotes on double quote strings and backslashes and single codes in single quoted strings).

Even with heredoc or nowdoc, you would still have a problem if you have a literal END; in the text you want to display. The only foolproof way is to put your literal text in a separate file, read it into a variable (with e.g. file_get_contents), and then echo that variable.

Related

Backslashes breaking string in PHP

I have an issue. I'm trying to write a string with ASCII text like this: '/\'. But whenever I do that the backslash screws up the code by canceling out the quote defining it a string therefore screwing it up. Is there anyway to cancel out the backslash so it doesn't cancel out the quote? Thanks guys!
The \ is special character, that says: 'The next character has special meaning'.
So if you want to dispaly \ you should write... \\ to get one \ in output
It would be very helpful to show what you have tried, but this will produce the exact output you requested (as shown by SO)
echo '\'/\\' . "'\n" ;
'/\'
It should also give you an idea of how backslash escaping works in different types of strings.
A great solution when writing stuff like that is HEREDOC. Inside a heredoc block you don't need to worry about escaping anything, it will just be text.
For example:
echo <<<TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
TEXT;
There is one catch. PHP will break if you don't align the echo at the start of the line, or if the TEXT; is not aligned at the start of the line.
Heredoc can also be assigned to a variable, like so:
$var = <<<SOME_MORE_TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
SOME_MORE_TEXT;
Finally, HEREDOC preserves tabs and spaces. Which also might come in handy when doing ASCII art.
Refer to: http://php.net/manual/en/language.types.string.php for more information.
You only need to escape the final one when using single quotes.
$var = 'backslash\backslash\backslash\\';
// output is:
// backslash\backslash\backslash\

using html and java script tags in php

I am confused about using single and double quotes and back slash while using java script and html tags in php can any one please clarify i googled it but still not clear about it. i am confused for this small thing.i am new to programming
- here is my code
<?php
if(isset($_GET['id'])) {
echo '<div id="d2">';
include "test2.php";
echo '</div>'; }
else
{
echo '<div id="d1">';
include "insert.php";
print "<script type=javascript>"
print "document.getEelementById('alertdiv1').innerHTML='hi' ;"
print "</script>"
echo '</div>';
}
?>
In PHP, you can enclose a string in either single quotes or double quotes. Both are valid:
$var = "this is a string";
$var2 = 'this is also a string';
The main difference is that if your string contains a variable, and you want the variable content to be treated as part of the string, you need to use double quotes:
echo "$var which I made";
will return:
this is a string which I made
When you are manipulating html, css and JavaScript strings, you need to make sure that you don't accidentally close your PHP string. For example:
echo "<h1 class='myheading'>Heading Text</h1>";
Notice how I used double quotes to enclose my string? Because I did that, I was able to use single quotes in the html, without escaping them.
If I'd wanted to use double quotes in my string, I would have had to escape them, like this:
echo "<h1 class=\"myheading\">Heading Text</h1>";
The \ tells PHP that the double quote which immediately follows is to be treated as a literal, and not used to terminate the string.
I can't see any problems relating to quotes in your code.
<script type=javascript> — That is not a valid value of the type attribute (which is optional anyway now). Get rid of the type attribute.
document.getEelementById — Element only has 3 es in it, not 4.
alertdiv1 — There is no element with that id in your code
hi as far as concerned single quotes and double quotes doesnt matters when its a string.but when you use any variable inside
$a = 'hi';
echo '$a' ;
will output
$a
but when you use " "
$a = 'hi';
echo "$a" ;
it will print
hi
Basically, if you're using "" (quotation marks) as your delimiter and you then use a quotation mark as part of the string you must escape it by putting a backslash in front of it.
For example:
$string = "This is my string"; // This is fine as the value of the string doesn't contain any quotation marks (")
$string = "I am including a quote in my string \"To Be Or Not To Be\"."; // This is also fine, as I have escaped the quotation marks inside the string
The same applies if you're using '' (apostrophes) as your delimiter and you then want to use them as part of the string, you must escape them using back slash ().
Hope that helps.
$var = "AAA";
echo 'This costs a lot of $var.'; // This costs a lot of $s.
echo "This costs a lot of $var."; // This costs a lot of AAA.

Escaping string before assigning to innerHTML echoed by PHP

I'm encountering a problem involving escaping character that I think it's not simple at all. If this is done in javascript, nothing to say but the context is using echo command (in PHP) to write javascript code like this:
echo "<script>document.getElementById('spanID').innerHTML=\"$x\"</script>";
$x is a variable in PHP environment, which can contain both single and double quotes. What I do here is:
1. Keep the $x not change, and if $x contains any double quote, the above code won't work, the text echoed may look like:
<script>document.getElementById('spanID').innerHTML="leftside"rightside"</script>;
I supposed $x = leftside"rightside, and you can see it surely won't work.
Escape the double quotes in $x (change all " to "), then the text echoed may look like this:
document.getElementById('spanID').innerHTML="leftside"rightside";
The " won't be converted to " when it is assigned to innerHTML attribute of a Span (for e.g), so instead of my want, the innerHTML of my SPAN should be leftside"rightside, it will be leftside"rightside.
If I change the " to ' in the original echo, like this:
echo "<script>document.getElementById('spanID').innerHTML='$x'</script>";
It is the same because $x here can contain both single and double quotes.
I don't find out any other ways to escape quotes in this case. Could you please help me out?
Thanks!
You need to put between the quotes a string that is a valid string of JavaScript containing valid (and safe) HTML.
Your best option is to not use innerHTML and instead use document.createTextNode which means you only need to slash-escape the content.
Otherwise, you need to HTML escape, then slash escape the content. For correctness, your slash-escaping function should escape at least double-quotes, backslashes, and all JavaScript newlines (U+A, U+D, U+2028, U+2029). I believe PHP's addslashes does not handle U+2028 or U+2029 by default but How to escape string from PHP for javascript? has some alternatives.
To put it all together:
$x_escaped = json_encode($x, JSON_HEX_TAG);
echo "<script>document.getElementById('spanID').appendChild(document.createTextNode($x_escaped))</script>"
should do it. The JSON_HEX_TAG makes sure that $x_escaped will not contain </script> or any other content that prematurely ends your script tag. </script> will instead become \u003c/script\u003e.

PHP writing Class and id as single quotes instead of double quotes. Why?

I am getting a lot of errors lately on a Joomla project and have found things like (in class code)...
return "<span class='...
or
echo "<h3 id='...
instead of
return "<span class=\"...
echo "<h3 id=\"...
This includes many times a variable in quotes, but it still finds it's way to my browser with single quotes. Before going through and changing these, I wanted to see what others have to say. My project is at http://dev.thediabetesnetwork.com.
I have looked this up and find a lot of conflicting information, so figured I would revive the discussion for the newest PHP/browser configurations and see if I am overlooking other details.
It's a lot easier to read without all the double quotes inside the string being escaped with \.
If you need to output a variable inside a string expression, double quotes must be used. If you are outputting HTML inside double-quotes, you can either use ' or \" to enclose HTML attributes. The first is preferred because it results in cleaner PHP code.
If you don't want your HTML to use single quotes, then you can just escape all of your quotes, use heredoc syntax, or concatenate your variables into the string like:
echo '<div class="test">' . $var . '</div>';
Browser accept both, thus there is no deeper reason to choose one before the other. From the PHP point-of-view it is slightly more readable with single quotes, because you can wrap strings in double quotes and use variable substition. Compare yourself
"<a href='$url'>Foo</a>"
"Foo"
'Foo'
Another solution is to substitute the content manually, for example
sprintf('Foo', $url);
Or heredoc
echo <<<HTML
Foo
HTML;
I would choose the one, that fits best into the current context (regarding the readability).
Double quote and single quotes have different functionality in php.
You can put a variable or even array into a string with double quotes but not so with single quotes.
Both are acceptable in HTML specification. Indeed even no quotes is if there's not spaces. Most people prefer that I know to have double quotes for the php so you can use variables without breaking up your code and readability because no backslashes.
return "<span class='foo'>$foo</span>";
return "<span class=\"foo\">$foo</span>";
return '<span class="foo">'.$foo.'</span>';
return '<span class=\'foo\'>'.$foo.'</span>';
All work but the first one, to most, is the easiest to read and type.
You can read all about php strings, double quotes, single quotes, heredoc and nowdoc syntax in php's documentation here: http://php.net/manual/en/language.types.string.php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
Is example Heredoc syntax which allows you to pick your starting and ending delimeters for long multiline strings. Nowdoc is the same as heredoc but like single quotes, you can't put variables into the string.
You don't need to use double quotes if the string doesn't need evaluating (e.g. if it contains variables, etc). In fact, because double quotes causes the string to be evaluated, they're less efficient than using single quotes and concatenating.
Furthermore, it's convention to use double quotes inside HTML tags, so this is how I'd do it:
return '<span class="test">' . $var . '</span>';
In my opinion, Joomla is very poorly coded, and what you've posted is just another example of this.
Another advantage to this method, as you can see above, is that code highlighters and IEDs make it easy to differentiate between "static" strings and variables.

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

Categories