PhpProcess
extends Process
in package
PhpProcess runs a PHP script in an independent process.
$p = new PhpProcess(''); $p->run(); print $p->getOutput()."\n";
Tags
Table of Contents
Constants
- ERR = 'err'
- ITER_KEEP_OUTPUT = 2
- ITER_NON_BLOCKING = 1
- ITER_SKIP_ERR = 8
- ITER_SKIP_OUT = 4
- OUT = 'out'
- STATUS_READY = 'ready'
- STATUS_STARTED = 'started'
- STATUS_TERMINATED = 'terminated'
- STDERR = 2
- STDIN = 0
- STDOUT = 1
- TIMEOUT_PRECISION = 0.2
Properties
- $exitCodes : mixed
- Exit codes translation table.
- $callback : mixed
- $commandline : mixed
- $cwd : mixed
- $env : mixed
- $exitcode : mixed
- $fallbackStatus : mixed
- $hasCallback : mixed
- $idleTimeout : mixed
- $incrementalErrorOutputOffset : mixed
- $incrementalOutputOffset : mixed
- $input : mixed
- $lastOutputTime : mixed
- $latestSignal : mixed
- $outputDisabled : mixed
- $process : mixed
- $processInformation : mixed
- $processPipes : PipesInterface
- $pty : mixed
- $sigchild : mixed
- $starttime : mixed
- $status : mixed
- $stderr : mixed
- $stdout : mixed
- $timeout : mixed
- $tty : mixed
- $useFileHandles : mixed
Methods
- __clone() : mixed
- __construct() : mixed
- __destruct() : mixed
- __sleep() : array<string|int, mixed>
- __wakeup() : mixed
- checkTimeout() : mixed
- Performs a check between the timeout definition and the time the process started.
- clearErrorOutput() : $this
- Clears the process output.
- clearOutput() : $this
- Clears the process output.
- disableOutput() : $this
- Disables fetching output and error output from the underlying process.
- enableOutput() : $this
- Enables fetching output and error output from the underlying process.
- fromShellCommandline() : static
- Creates a Process instance as a command-line to be run in a shell wrapper.
- getCommandLine() : string
- Gets the command line to be executed.
- getEnv() : array<string|int, mixed>
- Gets the environment variables.
- getErrorOutput() : string
- Returns the current error output of the process (STDERR).
- getExitCode() : int|null
- Returns the exit code returned by the process.
- getExitCodeText() : string|null
- Returns a string representation for the exit code returned by the process.
- getIdleTimeout() : float|null
- Gets the process idle timeout (max. time since last output).
- getIncrementalErrorOutput() : string
- Returns the errorOutput incrementally.
- getIncrementalOutput() : string
- Returns the output incrementally.
- getInput() : resource|string|Iterator|null
- Gets the Process input.
- getIterator() : Generator
- Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
- getLastOutputTime() : float|null
- Gets the last output time in seconds.
- getOutput() : string
- Returns the current output of the process (STDOUT).
- getPid() : int|null
- Returns the Pid (process identifier), if applicable.
- getStatus() : string
- Gets the process status.
- getStopSignal() : int
- Returns the number of the signal that caused the child process to stop its execution.
- getTermSignal() : int
- Returns the number of the signal that caused the child process to terminate its execution.
- getTimeout() : float|null
- Gets the process timeout (max. runtime).
- getWorkingDirectory() : string|null
- Gets the working directory.
- hasBeenSignaled() : bool
- Returns true if the child process has been terminated by an uncaught signal.
- hasBeenStopped() : bool
- Returns true if the child process has been stopped by a signal.
- inheritEnvironmentVariables() : $this
- Sets whether environment variables will be inherited or not.
- isOutputDisabled() : bool
- Returns true in case the output is disabled, false otherwise.
- isPty() : bool
- Returns PTY state.
- isPtySupported() : bool
- Returns whether PTY is supported on the current operating system.
- isRunning() : bool
- Checks if the process is currently running.
- isStarted() : bool
- Checks if the process has been started with no regard to the current state.
- isSuccessful() : bool
- Checks if the process ended successfully.
- isTerminated() : bool
- Checks if the process is terminated.
- isTty() : bool
- Checks if the TTY mode is enabled.
- isTtySupported() : bool
- Returns whether TTY is supported on the current operating system.
- mustRun() : $this
- Runs the process.
- restart() : static
- Restarts the process.
- run() : int
- Runs the process.
- setCommandLine() : $this
- Sets the command line to be executed.
- setEnv() : $this
- Sets the environment variables.
- setIdleTimeout() : $this
- Sets the process idle timeout (max. time since last output).
- setInput() : $this
- Sets the input.
- setPhpBinary() : mixed
- Sets the path to the PHP binary to use.
- setPty() : $this
- Sets PTY mode.
- setTimeout() : $this
- Sets the process timeout (max. runtime) in seconds.
- setTty() : $this
- Enables or disables the TTY mode.
- setWorkingDirectory() : $this
- Sets the current working directory.
- signal() : $this
- Sends a POSIX signal to the process.
- start() : mixed
- Starts the process and returns after writing the input to STDIN.
- stop() : int|null
- Stops the process.
- wait() : int
- Waits for the process to terminate.
- waitUntil() : bool
- Waits until the callback returns true.
- buildCallback() : Closure
- Builds up the callback used by wait().
- isSigchildEnabled() : bool
- Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
- updateStatus() : mixed
- Updates the status of the process, reads pipes.
- close() : int
- Closes process resource, closes file handles, sets the exitcode.
- doSignal() : bool
- Sends a POSIX signal to the process.
- escapeArgument() : string
- Escapes a string to be used as a shell argument.
- getDefaultEnv() : array<string|int, mixed>
- getDescriptors() : array<string|int, mixed>
- Creates the descriptors needed by the proc_open.
- prepareWindowsCommandLine() : string
- readPipes() : mixed
- Reads pipes, executes callback.
- readPipesForOutput() : mixed
- Reads pipes for the freshest output.
- replacePlaceholders() : mixed
- requireProcessIsStarted() : mixed
- Ensures the process is running or terminated, throws a LogicException if the process has a not started.
- requireProcessIsTerminated() : mixed
- Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
- resetProcessData() : mixed
- Resets data related to the latest run of the process.
- validateTimeout() : float|null
- Validates and returns the filtered timeout.
Constants
ERR
public
mixed
ERR
= 'err'
ITER_KEEP_OUTPUT
public
mixed
ITER_KEEP_OUTPUT
= 2
ITER_NON_BLOCKING
public
mixed
ITER_NON_BLOCKING
= 1
ITER_SKIP_ERR
public
mixed
ITER_SKIP_ERR
= 8
ITER_SKIP_OUT
public
mixed
ITER_SKIP_OUT
= 4
OUT
public
mixed
OUT
= 'out'
STATUS_READY
public
mixed
STATUS_READY
= 'ready'
STATUS_STARTED
public
mixed
STATUS_STARTED
= 'started'
STATUS_TERMINATED
public
mixed
STATUS_TERMINATED
= 'terminated'
STDERR
public
mixed
STDERR
= 2
STDIN
public
mixed
STDIN
= 0
STDOUT
public
mixed
STDOUT
= 1
TIMEOUT_PRECISION
public
mixed
TIMEOUT_PRECISION
= 0.2
Properties
$exitCodes
Exit codes translation table.
public
static mixed
$exitCodes
= [
0 => 'OK',
1 => 'General error',
2 => 'Misuse of shell builtins',
126 => 'Invoked command cannot execute',
127 => 'Command not found',
128 => 'Invalid exit argument',
// signals
129 => 'Hangup',
130 => 'Interrupt',
131 => 'Quit and dump core',
132 => 'Illegal instruction',
133 => 'Trace/breakpoint trap',
134 => 'Process aborted',
135 => 'Bus error: "access to undefined portion of memory object"',
136 => 'Floating point exception: "erroneous arithmetic operation"',
137 => 'Kill (terminate immediately)',
138 => 'User-defined 1',
139 => 'Segmentation violation',
140 => 'User-defined 2',
141 => 'Write to pipe with no one reading',
142 => 'Signal raised by alarm',
143 => 'Termination (request to terminate)',
// 144 - not defined
145 => 'Child process terminated, stopped (or continued*)',
146 => 'Continue if stopped',
147 => 'Stop executing temporarily',
148 => 'Terminal stop signal',
149 => 'Background process attempting to read from tty ("in")',
150 => 'Background process attempting to write to tty ("out")',
151 => 'Urgent data available on socket',
152 => 'CPU time limit exceeded',
153 => 'File size limit exceeded',
154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
155 => 'Profiling timer expired',
// 156 - not defined
157 => 'Pollable event',
// 158 - not defined
159 => 'Bad syscall',
]
User-defined errors must use exit codes in the 64-113 range.
$callback
private
mixed
$callback
$commandline
private
mixed
$commandline
$cwd
private
mixed
$cwd
$env
private
mixed
$env
= []
$exitcode
private
mixed
$exitcode
$fallbackStatus
private
mixed
$fallbackStatus
= []
$hasCallback
private
mixed
$hasCallback
= false
$idleTimeout
private
mixed
$idleTimeout
$incrementalErrorOutputOffset
private
mixed
$incrementalErrorOutputOffset
= 0
$incrementalOutputOffset
private
mixed
$incrementalOutputOffset
= 0
$input
private
mixed
$input
$lastOutputTime
private
mixed
$lastOutputTime
$latestSignal
private
mixed
$latestSignal
$outputDisabled
private
mixed
$outputDisabled
= false
$process
private
mixed
$process
$processInformation
private
mixed
$processInformation
$processPipes
private
PipesInterface
$processPipes
$pty
private
mixed
$pty
$sigchild
private
static mixed
$sigchild
$starttime
private
mixed
$starttime
$status
private
mixed
$status
= self::STATUS_READY
$stderr
private
mixed
$stderr
$stdout
private
mixed
$stdout
$timeout
private
mixed
$timeout
$tty
private
mixed
$tty
= false
$useFileHandles
private
mixed
$useFileHandles
= false
Methods
__clone()
public
__clone() : mixed
__construct()
public
__construct(string $script[, string|null $cwd = null ][, array<string|int, mixed>|null $env = null ][, int $timeout = 60 ][, array<string|int, mixed>|null $php = null ]) : mixed
Parameters
- $script : string
-
The PHP script to run (as a string)
- $cwd : string|null = null
-
The working directory or null to use the working dir of the current PHP process
- $env : array<string|int, mixed>|null = null
-
The environment variables or null to use the same environment as the current PHP process
- $timeout : int = 60
-
The timeout in seconds
- $php : array<string|int, mixed>|null = null
-
Path to the PHP binary to use with any additional arguments
__destruct()
public
__destruct() : mixed
__sleep()
public
__sleep() : array<string|int, mixed>
Return values
array<string|int, mixed>__wakeup()
public
__wakeup() : mixed
checkTimeout()
Performs a check between the timeout definition and the time the process started.
public
checkTimeout() : mixed
In case you run a background process (with the start method), you should trigger this method regularly to ensure the process timeout
Tags
clearErrorOutput()
Clears the process output.
public
clearErrorOutput() : $this
Return values
$thisclearOutput()
Clears the process output.
public
clearOutput() : $this
Return values
$thisdisableOutput()
Disables fetching output and error output from the underlying process.
public
disableOutput() : $this
Tags
Return values
$thisenableOutput()
Enables fetching output and error output from the underlying process.
public
enableOutput() : $this
Tags
Return values
$thisfromShellCommandline()
Creates a Process instance as a command-line to be run in a shell wrapper.
public
static fromShellCommandline(string $command[, string $cwd = null ][, array<string|int, mixed> $env = null ][, mixed $input = null ][, float|null $timeout = 60 ]) : static
Parameters
- $command : string
-
The command line to pass to the shell of the OS
- $cwd : string = null
-
The working directory or null to use the working dir of the current PHP process
- $env : array<string|int, mixed> = null
-
The environment variables or null to use the same environment as the current PHP process
- $input : mixed = null
-
The input as stream resource, scalar or \Traversable, or null for no input
- $timeout : float|null = 60
-
The timeout in seconds or null to disable
Return values
staticgetCommandLine()
Gets the command line to be executed.
public
getCommandLine() : string
Return values
string —The command to execute
getEnv()
Gets the environment variables.
public
getEnv() : array<string|int, mixed>
Return values
array<string|int, mixed> —The current environment variables
getErrorOutput()
Returns the current error output of the process (STDERR).
public
getErrorOutput() : string
Tags
Return values
string —The process error output
getExitCode()
Returns the exit code returned by the process.
public
getExitCode() : int|null
Return values
int|null —The exit status code, null if the Process is not terminated
getExitCodeText()
Returns a string representation for the exit code returned by the process.
public
getExitCodeText() : string|null
This method relies on the Unix exit code status standardization and might not be relevant for other operating systems.
Tags
Return values
string|null —A string representation for the exit status code, null if the Process is not terminated
getIdleTimeout()
Gets the process idle timeout (max. time since last output).
public
getIdleTimeout() : float|null
Return values
float|null —The timeout in seconds or null if it's disabled
getIncrementalErrorOutput()
Returns the errorOutput incrementally.
public
getIncrementalErrorOutput() : string
In comparison with the getErrorOutput method which always return the whole error output, this one returns the new error output since the last call.
Tags
Return values
string —The process error output since the last call
getIncrementalOutput()
Returns the output incrementally.
public
getIncrementalOutput() : string
In comparison with the getOutput method which always return the whole output, this one returns the new output since the last call.
Tags
Return values
string —The process output since the last call
getInput()
Gets the Process input.
public
getInput() : resource|string|Iterator|null
Return values
resource|string|Iterator|null —The Process input
getIterator()
Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
public
getIterator([int $flags = 0 ]) : Generator
Parameters
- $flags : int = 0
-
A bit field of Process::ITER_* flags
Tags
Attributes
Return values
GeneratorgetLastOutputTime()
Gets the last output time in seconds.
public
getLastOutputTime() : float|null
Return values
float|nullgetOutput()
Returns the current output of the process (STDOUT).
public
getOutput() : string
Tags
Return values
string —The process output
getPid()
Returns the Pid (process identifier), if applicable.
public
getPid() : int|null
Return values
int|null —The process id if running, null otherwise
getStatus()
Gets the process status.
public
getStatus() : string
The status is one of: ready, started, terminated.
Return values
string —The current process status
getStopSignal()
Returns the number of the signal that caused the child process to stop its execution.
public
getStopSignal() : int
It is only meaningful if hasBeenStopped() returns true.
Tags
Return values
intgetTermSignal()
Returns the number of the signal that caused the child process to terminate its execution.
public
getTermSignal() : int
It is only meaningful if hasBeenSignaled() returns true.
Tags
Return values
intgetTimeout()
Gets the process timeout (max. runtime).
public
getTimeout() : float|null
Return values
float|null —The timeout in seconds or null if it's disabled
getWorkingDirectory()
Gets the working directory.
public
getWorkingDirectory() : string|null
Return values
string|null —The current working directory or null on failure
hasBeenSignaled()
Returns true if the child process has been terminated by an uncaught signal.
public
hasBeenSignaled() : bool
It always returns false on Windows.
Tags
Return values
boolhasBeenStopped()
Returns true if the child process has been stopped by a signal.
public
hasBeenStopped() : bool
It always returns false on Windows.
Tags
Return values
boolinheritEnvironmentVariables()
Sets whether environment variables will be inherited or not.
public
inheritEnvironmentVariables([bool $inheritEnv = true ]) : $this
since Symfony 4.4, env variables are always inherited
Parameters
- $inheritEnv : bool = true
Return values
$thisisOutputDisabled()
Returns true in case the output is disabled, false otherwise.
public
isOutputDisabled() : bool
Return values
boolisPty()
Returns PTY state.
public
isPty() : bool
Return values
boolisPtySupported()
Returns whether PTY is supported on the current operating system.
public
static isPtySupported() : bool
Return values
boolisRunning()
Checks if the process is currently running.
public
isRunning() : bool
Return values
bool —true if the process is currently running, false otherwise
isStarted()
Checks if the process has been started with no regard to the current state.
public
isStarted() : bool
Return values
bool —true if status is ready, false otherwise
isSuccessful()
Checks if the process ended successfully.
public
isSuccessful() : bool
Return values
bool —true if the process ended successfully, false otherwise
isTerminated()
Checks if the process is terminated.
public
isTerminated() : bool
Return values
bool —true if process is terminated, false otherwise
isTty()
Checks if the TTY mode is enabled.
public
isTty() : bool
Return values
bool —true if the TTY mode is enabled, false otherwise
isTtySupported()
Returns whether TTY is supported on the current operating system.
public
static isTtySupported() : bool
Return values
boolmustRun()
Runs the process.
public
mustRun([callable $callback = null ][, array<string|int, mixed> $env = [] ]) : $this
This is identical to run() except that an exception is thrown if the process exits with a non-zero exit code.
Parameters
- $callback : callable = null
- $env : array<string|int, mixed> = []
Tags
Return values
$thisrestart()
Restarts the process.
public
restart([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : static
Be warned that the process is cloned before being started.
Parameters
- $callback : callable|null = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
Tags
Return values
staticrun()
Runs the process.
public
run([callable|null $callback = null ][, array<string|int, mixed> $env = [] ]) : int
The callback receives the type of output (out or err) and some bytes from the output in real-time. It allows to have feedback from the independent process during execution.
The STDOUT and STDERR are also available after the process is finished via the getOutput() and getErrorOutput() methods.
Parameters
- $callback : callable|null = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
Tags
Return values
int —The exit status code
setCommandLine()
Sets the command line to be executed.
public
setCommandLine(string|array<string|int, mixed> $commandline) : $this
since Symfony 4.2.
Parameters
- $commandline : string|array<string|int, mixed>
-
The command to execute
Return values
$thissetEnv()
Sets the environment variables.
public
setEnv(array<string|int, string|Stringable> $env) : $this
Parameters
- $env : array<string|int, string|Stringable>
-
The new environment variables
Return values
$thissetIdleTimeout()
Sets the process idle timeout (max. time since last output).
public
setIdleTimeout(int|float|null $timeout) : $this
To disable the timeout, set this value to null.
Parameters
- $timeout : int|float|null
-
The timeout in seconds
Tags
Return values
$thissetInput()
Sets the input.
public
setInput(string|int|float|bool|resource|Traversable|null $input) : $this
This content will be passed to the underlying process standard input.
Parameters
- $input : string|int|float|bool|resource|Traversable|null
-
The content
Tags
Return values
$thissetPhpBinary()
Sets the path to the PHP binary to use.
public
setPhpBinary(mixed $php) : mixed
since Symfony 4.2, use the $php argument of the constructor instead.
Parameters
- $php : mixed
setPty()
Sets PTY mode.
public
setPty(bool $bool) : $this
Parameters
- $bool : bool
Return values
$thissetTimeout()
Sets the process timeout (max. runtime) in seconds.
public
setTimeout(int|float|null $timeout) : $this
To disable the timeout, set this value to null.
Parameters
- $timeout : int|float|null
-
The timeout in seconds
Tags
Return values
$thissetTty()
Enables or disables the TTY mode.
public
setTty(bool $tty) : $this
Parameters
- $tty : bool
-
True to enabled and false to disable
Tags
Return values
$thissetWorkingDirectory()
Sets the current working directory.
public
setWorkingDirectory(string $cwd) : $this
Parameters
- $cwd : string
-
The new working directory
Return values
$thissignal()
Sends a POSIX signal to the process.
public
signal(int $signal) : $this
Parameters
- $signal : int
-
A valid POSIX signal (see https://php.net/pcntl.constants)
Tags
Return values
$thisstart()
Starts the process and returns after writing the input to STDIN.
public
start([callable $callback = null ][, array<string|int, mixed> $env = [] ]) : mixed
Parameters
- $callback : callable = null
-
A PHP callback to run whenever there is some output available on STDOUT or STDERR
- $env : array<string|int, mixed> = []
stop()
Stops the process.
public
stop([int|float $timeout = 10 ][, int $signal = null ]) : int|null
Parameters
- $timeout : int|float = 10
-
The timeout in seconds
- $signal : int = null
-
A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
Return values
int|null —The exit-code of the process or null if it's not running
wait()
Waits for the process to terminate.
public
wait([callable|null $callback = null ]) : int
The callback receives the type of output (out or err) and some bytes from the output in real-time while writing the standard input to the process. It allows to have feedback from the independent process during execution.
Parameters
- $callback : callable|null = null
-
A valid PHP callback
Tags
Return values
int —The exitcode of the process
waitUntil()
Waits until the callback returns true.
public
waitUntil(callable $callback) : bool
The callback receives the type of output (out or err) and some bytes from the output in real-time while writing the standard input to the process. It allows to have feedback from the independent process during execution.
Parameters
- $callback : callable
Tags
Return values
boolbuildCallback()
Builds up the callback used by wait().
protected
buildCallback([callable|null $callback = null ]) : Closure
The callbacks adds all occurred output to the specific buffer and calls the user callback (if present) with the received output.
Parameters
- $callback : callable|null = null
-
The user defined PHP callback
Return values
Closure —A PHP closure
isSigchildEnabled()
Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
protected
isSigchildEnabled() : bool
Return values
boolupdateStatus()
Updates the status of the process, reads pipes.
protected
updateStatus(bool $blocking) : mixed
Parameters
- $blocking : bool
-
Whether to use a blocking read call
close()
Closes process resource, closes file handles, sets the exitcode.
private
close() : int
Return values
int —The exitcode
doSignal()
Sends a POSIX signal to the process.
private
doSignal(int $signal, bool $throwException) : bool
Parameters
- $signal : int
-
A valid POSIX signal (see https://php.net/pcntl.constants)
- $throwException : bool
-
Whether to throw exception in case signal failed
Tags
Return values
boolescapeArgument()
Escapes a string to be used as a shell argument.
private
escapeArgument(string|null $argument) : string
Parameters
- $argument : string|null
Return values
stringgetDefaultEnv()
private
getDefaultEnv() : array<string|int, mixed>
Return values
array<string|int, mixed>getDescriptors()
Creates the descriptors needed by the proc_open.
private
getDescriptors() : array<string|int, mixed>
Return values
array<string|int, mixed>prepareWindowsCommandLine()
private
prepareWindowsCommandLine(string $cmd, array<string|int, mixed> &$env) : string
Parameters
- $cmd : string
- $env : array<string|int, mixed>
Return values
stringreadPipes()
Reads pipes, executes callback.
private
readPipes(bool $blocking, bool $close) : mixed
Parameters
- $blocking : bool
-
Whether to use blocking calls or not
- $close : bool
-
Whether to close file handles or not
readPipesForOutput()
Reads pipes for the freshest output.
private
readPipesForOutput(string $caller[, bool $blocking = false ]) : mixed
Parameters
- $caller : string
-
The name of the method that needs fresh outputs
- $blocking : bool = false
-
Whether to use blocking calls or not
Tags
replacePlaceholders()
private
replacePlaceholders(string $commandline, array<string|int, mixed> $env) : mixed
Parameters
- $commandline : string
- $env : array<string|int, mixed>
requireProcessIsStarted()
Ensures the process is running or terminated, throws a LogicException if the process has a not started.
private
requireProcessIsStarted(string $functionName) : mixed
Parameters
- $functionName : string
Tags
requireProcessIsTerminated()
Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
private
requireProcessIsTerminated(string $functionName) : mixed
Parameters
- $functionName : string
Tags
resetProcessData()
Resets data related to the latest run of the process.
private
resetProcessData() : mixed
validateTimeout()
Validates and returns the filtered timeout.
private
validateTimeout(float|null $timeout) : float|null
Parameters
- $timeout : float|null