Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PHP code/scripts on the command line

Tags:

linux

php

I just began learning PHP. I've installed php5 on Linux and wrote very simple code just to get going.

How can I run scripts? I tried using the -f option, but it works as a cat command and just spits out the code to standard output.

The interactive interpreter option works fine. Is a web browser the only way to execute a PHP script?

like image 691
kaiseroskilo Avatar asked Aug 06 '11 07:08

kaiseroskilo


People also ask

Can we use PHP for command line scripts?

As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.

How do I run a PHP file?

php” file is placed inside the “htdocs” folder. If you want to run it, open any web browser and enter “localhost/demo. php” and press enter. Your program will run.

How do I run a PHP script in Powershell?

Open powershell and type c:\php\php.exe -h , you will get the php help output. Yay you are up and running, whoot. Type env into os search (cortana) and select environmental variables. Now you can run php in powershell with php ( php -h to test).

Where can I run my PHP code?

A PHP code will run as a web server module or as a command-line interface. To run PHP for the web, you need to install a Web Server like Apache and you also need a database server like MySQL. There are various web servers for running PHP programs like WAMP & XAMPP.


2 Answers

A simple:

php myScript.php 

… should do the job.

If it is acting like cat, then you probably forgot to switch out of template mode and into script mode with <?php

like image 97
Quentin Avatar answered Sep 22 '22 06:09

Quentin


Shorter way for command line:

php -r 'echo "Hello "; echo "Jay";'
OR
php -r 'echo dirname("parent/child/reply") . "\n";'

like image 28
Jadeye Avatar answered Sep 22 '22 06:09

Jadeye