Skip to content
Advertisement

How can I execute PHP code with Powershell?

I’m building a website and I want to monitor a folder for changes, and when those changes happen I want to start my PHP script, which runs an SQL query to builds my table.
Here is the script: This is largely from nixda, so credit goes to them

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:xamppmysqldatadb"
    $watcher.Filter = "*myTable.csv*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                start-process -filepath \serverpathtophprunme.php
                Add-content "\serverpathtologlog.txt" -value $logline
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    Register-ObjectEvent $watcher "Changed" -Action $action
    Register-ObjectEvent $watcher "Deleted" -Action $action
    Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 5}

Advertisement

Answer

  • To synchronously execute console applications or batch files and capture their output, call them directly (c:pathtosome.exe ... or & $exePath ...), do not use Start-Process – see this answer.

  • .php script files are, at least by default, not directly executable, so you should invoke them by passing the script file path to php.exe as shown below (which runs them synchronously, with their stdout and stderr streams connected to PowerShell’s streams, if needed):

    • By default, if you do invoke a .php script-file path directly or directly pass it to Start-Process‘s -FilePath parameter, that script is opened for editing rather than getting executed.
php.exe -f \serverpathtophprunme.php 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement