Running Debian 9 and PHP 7.3, trying to execute a file with the php -f hello.php command. Instead of echoing hello it outputs the source code. The full code is
#!/usr/bin/php
<?
echo 'hello';
?>What I did:
- Confirmed the file has read and execute permissions.
- Confirmed the PHP shebang line is correct.
- Confirmed that PHP CLI tools are installed.
What is wrong? How to make it work?
2 Answers
When PHP parses a file, it looks for opening and closing tags, which are
<?phpand?>which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.PHP also allows for short open tag
<?(which is discouraged since it is only available if enabled using theshort_open_tagphp.iniconfiguration file directive, or if PHP was configured with the--enable-short-tagsoption).
(source)
So the most reliable solution is to use <?php instead of <? in your code.
That “shebang” is not needed:
#!/usr/bin/phpJust make your script this; note you should add the php to the opening short tag (<?):
<?php
echo 'hello';
?>Then run it like this:
php -f hello.phpOr even just leave out the -f and run it like this:
php ./hello.phpAnd then the output would be this:
helloAdditionally, when you say this:
- Confirmed the file has read and execute permissions.
PHP files do not have to have execute permissions; only read permissions since the file will be read and parsed by the PHP interpreter. Same for the command line as well as the Apache module PHP interpreter.