Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running CLI php script with execute bit

This has been bugging me slightly.

I know you can do

php foo.php

or

php -f foo.php

Is there no way to just launch a script with the execute bit set

./foo.php

Given the folowing:

#!/usr/bin/php

<?php 
exit('hello');

I get "Could not open input file" or " bad interpreter: No such file or directory" depending on if there's whitespace after "bin/php".

like image 467
Greg Avatar asked May 27 '26 15:05

Greg


2 Answers

Instead of #!/usr/bin/php, using #!/usr/bin/env php is a better solution. This will look up the PHP binary in the PATH environment variable. This is much more robust & crossplatform. BSD for example installs PHP in /usr/local/bin/php.

Further, you will need to make sure this is the first line, and that the script has the executable bit set, to set it for everyone (Generally OK) use: chmod a+x script.php

Also make sure you have the CLI SAPI enabled. Run php -v top verify, it should show something like:

[~]% php -v
PHP 5.3.3 (cli) (built: Jul 22 2010 16:21:30)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
like image 98
Martin Tournoij Avatar answered May 30 '26 04:05

Martin Tournoij


  1. Check if you have nothing before '#!', like an UTF-8 BOM
  2. Check if you don't have anything at the end of the line, like CR (\r) befor the final LF (\n). The CR goes there if you write the file in Windows with windows line endings (CR LF) and may be interpreted as a part of the interpreter path.
like image 32
Jacek Konieczny Avatar answered May 30 '26 04:05

Jacek Konieczny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!