29

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kaiseroskilo
  • 1,719
  • 4
  • 21
  • 29
  • If you are here (from a search engine hit) looking for a way to ***run PHP source directly from the command line*** (like a Perl one-liner), then go to Stack Overflow question *[How can I execute PHP code from the command line?](https://stackoverflow.com/questions/9520090/how-can-i-execute-php-code-from-the-command-line/60621329#60621329)*. (It is the `-r` option) – Peter Mortensen Oct 28 '21 at 18:23

4 Answers4

46

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
23

Shorter way for command line:

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

Jadeye
  • 3,551
  • 4
  • 47
  • 63
14

As already mentioned, you can execute your PHP with the following.

php myScript.php

If you wish to pass an argument(s), you can simply do so like this:

php myScript.php Apples

In your PHP file you can use this argument by accessing the $argv array like this:

<?php
    echo 'I like ' . $argv[1];
?>

The above would print our "I like Apples". Note the array index is 1 and not 0. 0 is used for script name. In this case $argv would be "myScript.php"

For more information, check out my blog post Running PHP from the Command Line - Basics.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jarrod
  • 9,349
  • 5
  • 58
  • 73
4

Actually, PHP's main purpose is to generate web pages, but there are at least two other options:

The first one can be achieved in many ways (eg. by giving proper permissions to the file and calling script by providing its URI, eg. ./index.php), the second one can be invoked by php -a command (as stated in the documentation mentioned above).

Vagabond
  • 877
  • 1
  • 10
  • 23
Tadeck
  • 132,510
  • 28
  • 152
  • 198