10

Is it possible to have php not to require the begin/end tags (<?php ?>) for some of the files? The code should be interpreted as php by default.

I'm aware that I can leave out the end tag (?>).

8
  • 2
    is there a specific reason that you dont want to do this? Commented Sep 6, 2009 at 15:24
  • 2
    This is not a sane default behavior. Don't do it. Commented Sep 6, 2009 at 16:03
  • 1
    @e.c.ho : just try ^^ you'll see it works (as long as you don't want any non-php code at the end of your file) ;; it is also recommended by coding standard of several frameworks (like Zend Framework, for instance) -- the point being that you cannot have white-spaces after the closing tag if there is no end tag. Commented Sep 6, 2009 at 17:18
  • 3
    @seengee In a MVC structure, the code looks ugly inside the controllers/models. I know it's not a big deal, but I've been coding php for 4 years, yet it it always felt wrong. Commented Sep 6, 2009 at 18:05
  • 3
    Everyone seems to be making the assumption that this is for web programming. PHP is quite usable as a general purpose scripting language as well. In that context the tags aren't always as useful. Commented Nov 24, 2009 at 2:34

6 Answers 6

18

If you'd like to call your PHP script from the command line, you can leave the script tags using the -r switch. Extract from man php:

   -r code        Run PHP code without using script tags ’<?..?>’

Now you can invoke your script in the following manner:

php -r "$(cat foo.php)"
Sign up to request clarification or add additional context in comments.

3 Comments

Then why this line php -r 'echo "Hello World!\n";' always throws error PHP Parse error: syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1 ?
@VickyDev not sure, it still works for me (PHP 7.1.16). What platform/version do you have?
Windows 7 64Bit and PHP 7.1.x stable, but it never works the way I mentioned, even-though, it has no syntax errors.
14

No. The interpreter needs the tags to know what to parse and what not to.

2 Comments

To add this this answer, anything outside of PHP tags is simply sent to the browser as text. PHP was originally intended as a templating language, whereby the PHP tags are interspersed with HTML, not the other way round.
Fair but a .php extension signals to a server to call a php interpreter anyhow.
7

It's better to not use end tag. Begin tag is neccesary.

As MaoTseTongue mentioned, in Zend documentation there is written:

For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.

5 Comments

I've heard this before, and I'm curious as to what? Is it to do with blank space at the end of the file causing problems (e.g. sending output before headers have been sent etc).
errr... by 'what' I meant 'why', sorry!
Do not include the closing php tag prevents "the accidental injection of trailing white space into the response". (see the [Zend Framework Documentation][1]). [1]: framework.zend.com/manual/en/…
It's fine to use the end tag (and aesthetically pleasing to those who like balance in their tags). The key point is not to include any trailing whitespace (eg. carriage return, line feed, tab, space, etc.) after the closing php tag because the web server will actually send those characters to the browser. Even then, for most web applications serving html, xml, json, it's generally harmless. But it can cause problems when dynamically building binary data such as an image. Another time it gets you into trouble is setting http headers when your php code has accidentally already sent whitespace.
just as empty lines before an <!doctyp html> might be a problem. Lets file a RFC
-1

Likewise you could make a text file that has a .php extension, and use another, 'real' php file to load that file, such as

Fake PHP file

php_info();

Real PHP file

<?
// file_contents returns a string, which can be processed by eval()
eval(file_get_contents('/path/to/file/'.urldecode($_GET['fakefile'])));
?>

In addition, you could use some mod_rewrite trickery to make the web user feel like they are browsing the php file itself (e.g. http://example.com/fakefile.php)

.htaccess file:

RewrieEngine On
RewriteRule ^(.*)$ realfile.php?fakefile=$1 [QSA]

However, if I remember correctly, your processing will be a little slower, and there are some issues with how evaled code handles $GLOBALS, $_SERVER, $_POST, $_GET, and other vars. You will have to make a global variable to pass these super globals into your evaluated code.

For example:

<?
global $passed_post = $_POST;
// only by converting $_POST into a global variable can it be understood by eval'ed code. 
eval("global $passed_post;\n print_r($passed_post);");
?>

Comments

-1

You can store PHP code in a file or database (without <?php ?>) and then activate it using eval(). Notice, the code will perform slower. An eval() example comes here:

// Data layer (array, database or whatever).
$arr = array("a","b","c");

// Code layer - hint: you can get the code from a file using file_get_contents().
$str = 'foreach($arr as $v) { echo $v . " "; }';

// Shake + Bake
eval($str);

Result: a b c

Comments

-2

This is a quote from another answer on superuser.com: (https://superuser.com/questions/612178/how-to-set-php-syntax-for-a-file-without-php-tag)

Put #<?php at the top of the file. PHP will treat it as a comment. Sublime won't. Perfect.

If helpful for anybody I also want to point out that this trick works for vscode. I am using this bc I have some software where i have to input pure php without open tag and i also save the whole code in a php file which requires the open php tag. With this comment trick i can still get syntax highlighting and also copy the whole file in the software where it will treat the first line as a comment.

6 Comments

This answer makes ABSOLUTELY no sense and should be deleted. Whatever trick meant here is likely just using regular PHP opening tag, with useless # which actually affects nothing (beside spoiling output). So it boils down to just adding a PHP tag. Zero sense.
Yeah i thought someone like that would pop up. I mean the file read from a pure php perspective is valid 'pure' php since the # comments out the line #<?php, but vscode treats the file as though the # is the "html" content before the open php tag thus it will highlight the actual code. I tried searching for a trick like this and nothing popped up so i thought i would post it here in case somebody finds it usefull, if not then well who cares?
First of all, in case you didn't notice, this particular question you decided to answer for some reason, NOWHERE mentions your "vscode". It is NOT about vscode AT ALL. Second, if yo remove that useless # the outcome will be just SAME, vscode will highlight the file all the same. And OBVIOUSLY, it doesn't answer the "no opening tag" question because you are actually using it.
I mean then also the question is weird bc ofcourse you need the opening tag, unless you specify compiler flags like -r in the first answer. My answer is not only about vscode its about any editor (eg the original answer said it for sublime). My issue was that i wanted code highlighting and to be able to copy paste the entire file in some plugin software that requires the 'pure' php code at the same time. If i removed the opening tag i dont get code highlighting, if i put in opening tag the software fails bc it wants pure php no <?php at the top... This is my solution. Does it now make sense?
No. I don't get what "software" you are talking about. Any software that recognizes PHP code, recognizes the opening tag as well. ANY software I know would treat both #<?php and <?php equally in every possible way. Besides, the answer you quoted is outright NONSENSE: "PHP will treat it as a comment" - PHP will NEVER treat it as a comment. So I still have no idea what are you talking about. In the end you ADDED the tag, which is contrary to what is asked here.
its niche, fabrik with joomla and for example the fabrik calc element you input php code in a textarea element and if you input with the opening tag at the top not comented out (the file starts with "<?php") it will throw an error. Where as the line #<?php is a commented out line, but u get highlighting... I realise that my solution is not without the opening tag, i said its a trick. # and // are comment markers. Although yes, my wording is bad php wont treat that as a comment in html scope like the compiler does, but will in pure php scope bc if line starts with # its a comme

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.