Run php code in command line

前端 未结 4 518
南笙
南笙 2021-01-01 10:38

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

相关标签:
4条回答
  • 2021-01-01 10:43

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

    • command line (CLI) script execution,
    • interactive shell - which is actually the variant of the previous option,

    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).

    0 讨论(0)
  • 2021-01-01 10:57

    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 info check out my blog post Running PHP from the Command Line - Basics

    0 讨论(0)
  • 2021-01-01 11:03

    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

    0 讨论(0)
  • 2021-01-01 11:09

    Shorter way for command line:

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

    0 讨论(0)
提交回复
热议问题