Skip to content
Advertisement

Command-line script PHP does not run

I am trying to build a PHP script to process data manually to later convert it to a cronjob. This script also gets data from MySQL and a third-party SOAP interface. When I try to run it from the command line I have an error and the script does not run.

It shows:

./test.php: line 1: ?php: No such file or directory
Enter a number:
./test.php: line 5: syntax error near unexpected token `('
./test.php: line 5: `$line = trim(fgets(STDIN));'

Here’s what I have in my script:

echo 'Enter a number: ';
$line = trim(fgets(STDIN));
var_dump($line);

I know this script works. What is wrong?

Advertisement

Answer

You get this error because you execute this script like ./script.php. In order to make sure the PHP script understand and run properly, you have to include #!/usr/bin/php at the top of your script.

Example:

#!/usr/bin/php
<?php
echo 'Enter a number:';
$line = trim(fgets(STDIN));
var_dump($line);

If PHP is installed in the /usr/bin folder. If not, you can verify using the locate php command and then use the right path.

Or the other alternative will be

php /path/to/script.php
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement