How can I avoid displaying "#! / Usr / bin / php" in PHP?

I want PHP scripts to run both on the command line and on the website (I use Apache and Nginx), so I put #! / Usr / bin / php on the first line of my scripts, but this appears on the website ...

+7
command-line-interface php shell apache nginx
source share
5 answers

I solved the problem with output buffering. My script now looks like this:

#!/usr/bin/php <?php @ob_end_clean(); ... 

Note. No file at the end ?> . This is really good practice when writing PHP scripts. This prevents accidental printing of any garbage.

Note. The PHP documentation for ob_end_clean() says that:

The output buffer should be started using ob_start () with the PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise, ob_end_clean () will not work.

This seems to be done automatically when PHP starts from the command line.

+17
source share

There is no need to have #!/usr/bin/php in your code, just run the CLI script with php like php /path/to/file.php or /usr/bin/php /path/to/file.php .

+5
source share

I usually find it a good idea to separate the logic from the presentation. When I do something like this, I put as much as possible into the library, and then write separate cli and web interfaces for it.

However, calling it with the php command is probably an easier solution.

+3
source share

Call script using php command

+1
source share

The above buffer solution is a hack. Do not do this.

First, you really better use the env command to determine which php is used:

 #!/usr/bin/env php 

Then give it permission to do it yourself:

 chmod +x myfile 

So instead of calling 'php myfile', you now simply run:

 ./myfile 

From this folder. Hope this helps!

-one
source share

All Articles