“php -f” doesn’t run code but only shows file contents

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 <?php and ?> 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 the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).

(source)

So the most reliable solution is to use <?php instead of <? in your code.

4

That “shebang” is not needed:

#!/usr/bin/php

Just 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.php

Or even just leave out the -f and run it like this:

php ./hello.php

And then the output would be this:

hello

Additionally, 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like