在apache2启动时启动php脚本

问题描述

我正在尝试运行PHP脚本,以在服务器崩溃,重新启动或启动后恢复状态。 因为PHP脚本需要数据库运行,所以我首先尝试在init.d中创建一个文件来运行它,该文件不起作用,它只是在需要时才启动。 因此,现在我认为这是在apache2启动上运行脚本的最简单方法,如描述为here。 因此,目前我已将PHP -q /var/www/scripts/testing.PHP & ;;添加do_start()中的/etc/init.d/apache2中,如下所示:

do_start()
{
        # Return
        #   0 if daemon has been started
        #   1 if daemon was already running
        #   2 if daemon Could not be started

        if pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                return 1
        fi

        if apache_conftest ; then
                $APACHE2CTL start
                PHP -q /var/www/scripts/testing.PHP &
                ;;
                apache_wait_start $?
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest Failed."
                return 2
        fi
}

但是,因为这根本不起作用,所以我还将该PHP执行添加到了链接中提到的restart)部分。看起来像这样:

 restart)
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop stop
        case "$?" in
                0|1)
                        do_start
                        case "$?" in
                                0)
                                        log_end_msg 0
                                        ;;
                                1|*)
                                        log_end_msg 1 # Old process is still or Failed to running
                                        print_error_msg
                                        exit 1
                                        ;;
                        esac
                        ;;
                *)
                        # Failed to stop
                        log_end_msg 1
                        print_error_msg
                        exit 1
                        ;;
        PHP -q /var/www/scripts/testing.PHP &
        ;;
        esac
        ;;

但是脚本仍未运行。 PHP脚本如下所示:

<?PHP
file_put_contents('/var/www/html/log',"301,$timestamp,Recreating all connections after restart,N/A\n",FILE_APPEND);
?>

因为我希望它尽可能简单,但是日志文件仍然为空。我愿意解决我的问题。

ps:我已经尝试通过/etc/systemd/system/中的服务来执行此操作,但是由于我正在启动应该是持久的连接,因此我必须使用screen,{{1} }或nohup。我已经尝试了这三个,但是没有一个奏效,只是他们没有启动脚本。 (当时是bash,我切换到PHP以便能够从apache2文件运行它)

解决方法

您不应该使用apache启动脚本,而是遵循使用自己的初始化脚本的第一个想法,除非您的php脚本依赖于apache的存在。

只需将外壳程序脚本callmyphp放到/etc/init.d中,该脚本会调用php解释器并将php脚本作为参数传递,例如:

#!/bin/sh
/usr/bin/php -q /path/to/myphp.php

别忘了使用chmod 755 /etc/init.d/callmyphp使调用脚本执行。

然后通过符号链接将调用脚本添加到所需的运行级别,即通过运行update-rc.d callmyphp defaults

另请参阅https://debian-administration.org/article/28/Making_scripts_run_at_boot_time_with_Debian