Run PHP script in background on Apache start/restart(Windows Server) Run PHP script in background on Apache start/restart(Windows Server) php php

Run PHP script in background on Apache start/restart(Windows Server)


I come up with a solution :)

  • Create an environment variable pointing to your Apache directory

    APACHE_HOME = C:/PATH/TO_APACHE

  • Rename %APACHE_HOME%\bin\httpd.exe to %APACHE_HOME%\bin\httpdVendor.exe
  • Create a batch file and put the following code :

    php myscript.php%APACHE_HOME%\bin\httpdVendor.exe -k runserviceexit 0

  • Download/Install the free software BatToExeConverter (next, next, ...)
  • Open the installed converter and open your freshly created batch file
  • Click on the button Build EXE (let the default configuration)
  • Save the file : %APACHE_HOME%\bin\httpd.exe
  • Start your Apache Server
  • Tested on : Windows 7, Apache 2.4, Advanced Bat to Exe Converter 2.92


    Use built in Windows Task Scheduler which triggers .bat script, which calls curl with defined url.

    1. Download curl from http://curl.haxx.se/download.html and extract curl.exe on any directory, but we will use c:\backgroundtasks
    2. Adjust script below to your needs:

      cd c:\

      cd c:\backgroundtasks

      curl http://localhost/path/to/script.php

      exit

    3. Configure Task Scheduler to run as basic task:

      • General tab - as system account (to run when you are not logged in server)
      • Triggers tab - adjust frequency
      • Settings tab - at bottom set If the task is already running... to Stop the existing instance


    The best method here would be to use Windows services dependencies.

    Make a php-websocket-server.cmd file with any necessary environment settings (e.g. changing to a directory, setting PATH, etc...) with the last line:

    php myscript.php

    Install the Windows Server Resource Kit Tools, to get srvany and instsrv to create a user defined service. Note the install path as you'll need it in the next step.

    Open a cmd shell and run:

    <path_to_resource_kit>\instsrv PHPWebSocketServer <path_to_resource_kit>\srvany.exe

    Next, create a file php-websocket-server.reg containing the following (update for your environment):

    Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PHPWebSocketServer\Parameters]"Application"="c:\\path\\to\\php-websocket-server.cmd"

    Import it by double-clicking or regedit /s php-websocket-server.reg

    Back in your cmd shell:

    sc config Apache2.4 depend= PHPWebSocketServer

    to make the Apache2.4* service depend on your php service. Now, when Apache is started, the php service will be brought up first. And likewise, if you stop the php service Apache will stop along with it.

    *the howto indicates that the service is named "Apache2.4" but you may want to verify in your installation.