how to use <<< tag in php - php

I am following a book tutorial where the author do like this to display html
eks:
return <<<ADMIN_OPTIONS
+ add a new event
<form action="assets/inc/process.inc.php" method="post">
<div>
<input type="submit" value="Log Out" class="admin" />
<input type="hidden" name="token" value="$_SESSION[token]" />
<input type="hidden" name="action" value="user_logout" />
</div>
</form>
ADMIN_OPTIONS;
I don't quite understand the <<<, from my understanding you can call ADMIN_OPTIONS whatever as long as you end the html with the same words. The thing I really don't understand though is when I write ADMIN_OPTIONS; and all my code goes in comment mode. For example:
The above example works, this does not:
return <<<ADMIN_OPTIONS
Log In
ADMIN_OPTIONS;
but this works:
return <<<ADMIN_OPTIONS
Log In
ADMIN_OPTIONS;

As others mentioned, this is called heredoc.
You can choose the identifier freely. It's very similar to using double quotes, you can embedd variables with {$var} too. Because of that you also can't use them in any static context, like a default value in a class, consts or define()s. That's why nowdocs were introduced (in PHP 5.3).
If you read the manual entry, you'll quickly find out why your example doesn't work; there
must not be any spaces or tabs in front of the ending identifier.
From the manual:
It is very important to note that the
line with the closing identifier must
contain no other characters, except
possibly a semicolon (;). That means
especially that the identifier may not
be indented, and there may not be any
spaces or tabs before or after the
semicolon. It's also important to
realize that the first character
before the closing identifier must be
a newline as defined by the local
operating system.

It's Heredoc. Not usually used often.
I think your second example doesn't work because the end identifier line is not "clean". There's a space after the semicolon, whereas the first and third examples are clean.

The syntax you are using is called heredoc, and it is explained in the following section of the PHP manual:
http://php.net/manual/en/language.types.string.php
Basically all it is is an alternative to encapsulating strings within quotes.

These are exactly the same as:
return "
foo bar
";
The difference is that you can specify the termination character sequence yourself, i.e. you're not limited to quotes to start and end your string.
return <<<TERMINATIONSEQUENCE
Because I'm not limited to "quotes",
I can 'freely' use them in "this 'string"'
without worrying about escaping them!
TERMINATIONSEQUENCE;

This is called Heredoc, they behave exactly like strings with double quotes, except without the double quotes.. thus you don't need to escape those.
It also preserves the line breaks and other whitespace in the text.
The ADMIN_OPTIONS is just a identifier to open and close the operation.

You've got a space after the semicolon in the non-working example, that's why PHP doesn't recognize it.

After viewing the source of the OP one can notice that the spacing and tabulation is not identical in the second case to the first & third cases.
Heredoc like mentioned by many requires that your terminator be the only item on the line. You cannot have a tab, or any other white space preceding it.
Good luck!

Related

HOW TO PRINT "THAT'S IT!" IN PHP? WITH DOUBLE AND SINGLE QUOTATIONS? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to print "that's it!" Exactly as same with double and single quotations in php? Can anyone have solution?
You just have to escape the single quote with a back slash
echo '"that\'s it!"';
I'll post something different because I like them and it think it's often missed or unknown by less experienced programmers.
HereDoc/NowDoc
//HereDoc works like " for variables
echo <<<TXT
"that's it!"
TXT;
The TXT tag can be anything that follows the same rules as variable names (\w+, and must start with Alpha), and the ending one must be on it's own line with "ABSOULTLY" nothing else besides ; (which can be omitted in arrays), nothing else not even whitespaces.
//NowDoc works like ' for variables
echo <<<'TXT'
"that's it!"
TXT;
It's often overlooked, as it's not documented in any really visible place, it's the third example on the string type page on PHP.net. Then after a bunch of scrolling you'll find the Nowdoc part, the only real difference is how they treat variables, as I mentioned.
http://php.net/language.types.string#language.types.string.syntax.heredoc
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Warning
It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including macOS. The closing delimiter must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
This is also common in other languages besides PHP (with minor variations), and it's the cleanest way (for larger amounts of text, think HTML, JavaScript and a mix of those and PHP).
$selector = 'a.foobar';
echo <<<HTML
<script type="text/javascript">
;( function( $, window, document, undefined ) {
"use strict";
$(document).ready(function(){
$('tr.foobar').css('display', 'none');//singe quotes are fine
$("div.foobar").css("display", "none");//double quotes are too
$({$selector}).css('display', "none");//we can even mix them up if we want.
//we can use PHP variable like {$selector}, even these
//comments become comments in the JS.
//if that wasn't enough, most IDE's treat them like HTML
//so they are not greyed out, but nicely colored!
});
} ) ( jQuery, window, document );
</script>
HTML;
And this would work just fine, even the {$selector} would be replaced by PHP, the {} are optional except for method calls (unless they changed that). I put them in by habit because it colors them better in my IDE. Which is excatly how PHP treats variables in "normal" double quoted strings. (variable interpolation) except here we can use both types of quotes any way we want to...
If you do ever put one in an array it will only work this way (without the ;):
$a = [
<<<TXT
sometext
TXT
, "something else",
1,
2,
'etc..'
];
Other languages that use them (linked to the PHP section)
https://en.wikipedia.org/wiki/Here_document#PHP
In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace (including indentation) in the text.
The important thing is it does not use the quotes to define the string, so you are free to use them however you want, with no escaping.
One last thing I happened to notice from the PHP documentation that i never really read before.
the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including macOS
Maybe someone else knows, but I am not sure how important this bit really is. I program on a Windows Desktop \r\n, and then use the same exact files on a Linux server \n and Have Never 1 time had an issue with what that says. I do use editors though like Eclipse PDT, so it may default to the \n even on windows. But I have never had an issue on either one....
Enjoy!!
Probably one of the ways that works without escaping is as follows:
echo('"'."that'".'s it!"');

Is it safe to concatenate a double quoted to a single quoted string?

Are there any issues I should be aware of when doing the following:
$table_html = ' <td id="unescaped-double-quotes-yay">Some stuff</td>' . "\n";
I do not like escaping double quotes withing HTML and I can't stand using single quotes in HTML, my solution is what I have above. Am I going to run into any issues with this practice?
You MUST escape strings that comes from DB or from the user because they could easily break you concatenation if the unexpected kind of quote is present in that string (not to mention that you MUST cleanse anything that comes from the user for minimal security).
Other than that you can concatenate strings any way you like. Still, life will always be easier if you manage to use them cosistently the same way.
I have done this many times on client sites (have since found better alternatives), you are 100% fine.
Are you aware of the following representation:
$table_html = <<<HTML
<td id="unescaped-double-quotes-yay">
Some stuff, and i can use normal newlines here
</td>
HTML;
It is called "heredoc", and you must keep in mind that the final string must be equivalent to the opening one, and must be the only thing on the line (no spaces or even comments are allowed).
You must also terminate the last line with the newline, even if it is the last line in the file.
To read more about it click here

PHP What the meaning or use of echo << JS "some javascript code " JS;? [duplicate]

I've been developing with PHP for some years now, and recently came across this code:
<?php
echo <<<EOB
<html>
<head>
<title>My title</title>
</head>
...
EOB;
?>
I've never seen this approach to print HTML, which seems to be pretty useful and less prone to some weird variable or double quote syntax error.
I've searched for some official information about this and only found a post of Rasmus talking about this.
What is a detailed explanation about this functionality and what does EOB mean? Maybe end of block?
This is known as heredoc syntax. The documentation will tell you everything you need to know.
Essentially, however:
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
So EOB is just what the author chose as his delimiter, not really sure what it stands for in his case but the identifier can be whatever you want.
Just for the sake of completeness, Heredoc in PHP is inherited from Perl, which itself inherited it from the Bourne shell.
It´s called heredoc and is described in the manual.
The official term is 'here document' I believe, usually shortened to 'heredoc'.
This is called heredoc syntax. It lets you treat large blocks of text like a string. It allows for newlines as well. Variables can be inserted into the block of text, just like using the double quotation marks for strings.
A more useful explanation can be found on PHP's own website: http://php.net/manual/en/language.types.string.php

PHP - Problem with script tags within the php code

I am editing some code that I've inherited from elsewhere and there seems to be a problem with the script tags in this section of the code. If I remove them the page runs but obviously the javascript does not run.
I'm not too good with php so I'm not sure how to fix this.
$GLOBALS['TEMPLATE']['extra_head'] = <<<ENDHTML
<script src='js/ajax.js' type='text/javascript'></script>
<script src='js/blog.js' type='text/javascript'></script>
ENDHTML;
Just a guess, but if there are any characters (including spaces or tabs) on the same line before or after the closing delimiter of the HEREDOC, you will get errors.
From the manual:
Warning
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
What you eluded to (blank screen and broken syntax highlighting in your text editor) would be the result or symptom of a parse error if error reporting is off. It's hard to see if this is the case in your post, being outside the context of the actual file.
Check that out and see if it is applicable.
Aside: It's a good habit to turn on error_reporting(E_ALL) while in development.
Those 'tags' just allow you to enter bare HTML within PHP code without having to use quotations etc.
It's assigning anything between those 2 tags to the variable: $GLOBALS['TEMPLATE']['extra_head']

PHP expression <<<EOB

I've been developing with PHP for some years now, and recently came across this code:
<?php
echo <<<EOB
<html>
<head>
<title>My title</title>
</head>
...
EOB;
?>
I've never seen this approach to print HTML, which seems to be pretty useful and less prone to some weird variable or double quote syntax error.
I've searched for some official information about this and only found a post of Rasmus talking about this.
What is a detailed explanation about this functionality and what does EOB mean? Maybe end of block?
This is known as heredoc syntax. The documentation will tell you everything you need to know.
Essentially, however:
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
So EOB is just what the author chose as his delimiter, not really sure what it stands for in his case but the identifier can be whatever you want.
Just for the sake of completeness, Heredoc in PHP is inherited from Perl, which itself inherited it from the Bourne shell.
It´s called heredoc and is described in the manual.
The official term is 'here document' I believe, usually shortened to 'heredoc'.
This is called heredoc syntax. It lets you treat large blocks of text like a string. It allows for newlines as well. Variables can be inserted into the block of text, just like using the double quotation marks for strings.
A more useful explanation can be found on PHP's own website: http://php.net/manual/en/language.types.string.php

Categories