vise
vise

Reputation: 13393

Php without start/end tags?

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 (?>).

Upvotes: 11

Views: 14346

Answers (5)

Kristoffer Bohmann
Kristoffer Bohmann

Reputation: 4104

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

Upvotes: -1

viam0Zah
viam0Zah

Reputation: 26312

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

Upvotes: 18

Tony G.
Tony G.

Reputation: 17

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

Upvotes: 0

Thinker
Thinker

Reputation: 14464

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.

Upvotes: 7

code_burgar
code_burgar

Reputation: 12323

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

Upvotes: 14

Related Questions