doufan9395 2016-01-24 05:14
浏览 113
已采纳

如何通过输入文件名从命令行执行PHP脚本?

I want to be able to type into the command line, and have the following PHP script execute like so:

$ hello.php

Question is, where do I save my hello.php file to run it like this. I see a lot of tutorials showing this way, but they do not mention where to save the actual file. If I save it on my desktop then it will run when I type in:

~/Desktop/hello.php

I want to be able to just type in the file name regardless of what directory I'm in and have it execute.

Do I have to setup an alias? Or can I just put it in a specific folder.

hello.php

<?php

echo 'Hello! This is a test';
  • 写回答

2条回答 默认 最新

  • duanmajing9332 2016-01-24 05:22
    关注

    All you have to do is add a shebang line:

    #!/usr/bin/php
    <?php
    
    echo 'Hello! This is a test';
    

    And then:

    chmod +x hello.php
    

    Then you can run it from the same directory by just typing:

    ./hello.php
    

    If you want to be able to run it from anywhere, put it somewhere in $PATH, such as /usr/local/bin. You can either actually put the file there, or change your PATH, or create a symbolic link. Then, you can run it as:

    hello.php
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?