命令行运行 PHP

Posted on 20th March 2007 by Nio in 程序人生

Command-line PHP? Yes, you can!

The benefits of CLI PHP

For many years now, I've been applying a dubious definition of what it means to be an engineer. By my reckoning, an engineer is someone who uses a tool for something other than its originally intended purpose. While that isn't always a good idea, when you get down to it all, invention and, indeed, most innovation come from using something in a way you hadn't necessarily thought to use it before.

Imagine my surprise, then, when the idea hit me to use my old friend PHP, which has always been so reliable on Web pages, as a command-line tool. I'm hardly the first person to do this, but the idea was certainly new to me.

Of course, just the fact that you can use PHP on the command line isn't necessarily the best reason for doing so. However, you might quickly find several pleasant surprises when you first begin to experiment with PHP in this way. To begin with, debugging existing scripts becomes far, far simpler than ever. Programs that consist primarily of output with very little logic are incredibly simple in PHP. Beyond that, you can use all your knowledge of PHP to make it accomplish tasks you would never have thought of it for before. In fact, there's really nothing stopping you from using PHP as your Swiss Army knife for almost any given programming project.

Intrigued? Well, let's get started and see what you can accomplish by using PHP on the command line.

记得很早之前,我也经常写一些 PHP 脚本,放在 Linux 服务器上运行,比如自动打包、加密之类的,使用起来非常方便,当然前提是你必须熟悉 PHP ;)

8 Comments »

  1. 看标题还以为你会说几个实用的应用呢。
    被骗了,被骗了

    Comment by xLight — March 20, 2007 @ 2:36 pm

  2. 哈哈,不好意思,最近比较忙,没怎么更新 blog

    Comment by Nio — March 20, 2007 @ 8:24 pm

  3. 最近想做用php来调用命令行的东西,但是权限不好搞,用了suphp,发现只支持cgi方式运行的php …

    Comment by easy — March 20, 2007 @ 10:55 pm

  4. php 命令行还是适合通过 cron 调用或者直接运行,通过 WEB 方式比较麻烦,而且不安全。

    Comment by Nio — March 21, 2007 @ 10:24 am

  5. 主要是想做一个基于web的部署系统,可以进行版本控制,单元测试和代码部署。一般是在内部开发环境上部署,所以安全性可以稍微低一点。

    Comment by easy — March 21, 2007 @ 5:31 pm

  6. 嘿嘿,我也正在弄这个,基本命令行都差不多了,可以增加 trac,svn 仓库,管理访问用户权限,svn 提交之后自动部署等等,这些都基本完成了,还需要加入 web 管理功能,哈哈。我初步的想法是通过 php 写文件(比如xml),然后再用 cron 运行一个程序分析这些文件,根据文件内容执行创建项目之类的动作,可以把 cron 的时间设置短一些,这样延迟也可以接受。

    Comment by Nio — March 22, 2007 @ 9:48 am

  7. 我们公司曾经定时cvs update的
    后来网站规模有些大了。update 过慢,就又改成手工ftp传了(此方法被我严重鄙视,完全可以用perl记录并单独update更新过的文件嘛)。

    Comment by xLight — March 30, 2007 @ 10:23 am

  8. 有谁知道如何向命令行传递一个数值,像get一样。

    Comment by bill — April 28, 2007 @ 2:00 pm

Leave a comment