If you want to run php script in shell, simply put the following line at the beginning of your php file.
#!/path/to/php
#!/path/to/php is the path you installed php in linux. If you don’t know where php is installed in your linux. Type the following command
which php
This will output the php path from your linux. The output will be something like this
/usr/bin/php
For example: hello.php
#!/usr/bin/php <?php echo "Hello World!"; ?>
Make your php script executable by typing
chmod +x hello.php
And then run it
./hello.php
You’ll see
Hello World!
Comments
18 responses to “How to run php script in shell”
good tutorial more power to you
Great simple basic tutorial. Thanks…
And what if hello.php contains the following?
#!/usr/bin/php
How do I call hello.php with argument msg=hello+world?
The following doesn’t work:
php hello.php?msg=hello+world
Ooops, the php tag are interpreted!
And what if hello.php contains the following?
How do I call hello.php with argument msg=hello+world?
The following doesn’t work:
php hello.php?msg=hello+world
How would you do this with cmd in windows.
@santiago: I know it is kind of strange to expect to GET Parameters.. but I am searching for the same as I would like to implement a cronjob that would need some input-variable.
I tried as vector:
./hello.php -msg hello
to no avail..
ok .. solution:
and catch it in PHP with
Caution!: on index 0 you woulg get “./hello.php”
Great! Thanks a lot man!
Hi expert,
How can run bellow line using bash script
http://10.1.4.8/corp_bulk.php?user=xyz&pass=123&ms=test&text=test
Thanks in advance.
Faruk
thanks! that was very helpful.
I did at some point know this stuff, but I needed to know it again tonight, and now I do!
:)
When I run ‘which php’….It shows me result as below
/usr/bin/php
I added the following line to my script
#!/usr/bin/php
But when I execute the script like ‘./script.php’, it shows me error as below.
-bash: ./script.php: /usr/bin/php^M: bad interpreter: No such file or directory
Please suggest what could be wrong here?
Thanks in advance …
Hey Rahul VK Khandelwal,
Your file might be in the wrong format. DOS format (newline is \r\n) instead of unix format (newline is \n).
Good luck
Santiago
Thanks a ton Santiago. I changed the format with dos2unix and it worked for me.
Thanks!
[…] Create a PHP shell script: […]
thanks a lott..!
On web servers where more then 2 php versions are installed “which php” can cause a problem. In my case the path was the path to the 4.2 version. I had to ask the hosting provider the right path.
But a very good tutorial!
Is it feasible and/or advisable to combine shell/apache usage in one file?
I have a group of tasks that have to be called from website AND cronjob.
Can i use php in apache2 REGULARLY that contain the line #!/usr/bin/php ?
Will i be disappointed and give up on using parameters of both cases?
Thanks!