PHP是一种解释型的编程语言,如果没有解释器,PHP程序其实和普通文本并没有什么区别。也因为此PHP的执行必须依赖PHP的运行环境。在开发过程中我们很容易把一个可执行的程序加入到服务器的开机启动项中,但是PHP因其特殊性,对于刚入门的新手显得略微复杂,所以本篇文章波波分享的就是如何把一个PHP文件加入到开机启动项中。
环境配置:Centos+php7.2
方法一:修改服务器启动项。
这是最简单的方法,尤其适合新手采用。
1、SSH登录服务器,打开并编辑“/etc/rc.local”文件。
2、复制如下内容,追加到文件中“exit 0”前面的位置。
- /usr/bin/env php /磁盘/路径/test.php start -d
- exit 0
方法二:脚本启动。
这种方式一般适合熟悉SHELL编程的老鸟。
1、我们需要将需要启动的php脚本文件赋予可执行权限。
- chmod +x /磁盘/路径/test.php
2、编写启动脚本。以下代码是我从网上找来的样本仅供参考。
- #!/bin/bash
- #chkconfig:2345 90 10
- #description:activitytask service
- #processname:activitytask
- php=/usr/bin/php
- root_path="/vagrant/activity_task/"
- start_file="web_start.php"
- case "$1" in
- start)
- echo 'starting activity_task web_start.php'
- echo "$php ${root_path}${start_file} start -d"
- $php ${root_path}${start_file} start -d
- ;;
- stop)
- echo "stoping activity_task...web_start.php"
- echo "$php ${root_path}${start_file} stop"
- $php ${root_path}${start_file} stop
- ;;
- status)
- echo "status activity_task...web_start.php"
- echo "$php ${root_path}${start_file} status"
- $php ${root_path}${start_file} status
- ;;
- restart)
- echo "restarting activity_task...web_start.php"
- echo "$php ${root_path}${start_file} reload"
- $php ${root_path}${start_file} reload
- ;;
- *)
- echo "Usage: $0 {start|stop|restart|restart}"
- exit 1
- ;;
- esac
上面这个脚本比较全,有点类似服务的启动,停止与重启。单纯的开机启动要比这个简单的多。切记上述脚本也要赋予可执行的权限。
3、配置开机启动。
- chkconfig service_name on
当然开机启动的方法不止这两种,还可以通过其他外部插件进行实现。更多操作方法自己摸索吧!