How to Stop PhantomJS Processes From Hanging After PHP shell_exec
Diagnose whether PHP is waiting on a shell, open pipes, or PhantomJS page work, then run captures with controlled arguments, output handling, and timeouts.

If PHP appears stuck after shell_exec() launches PhantomJS, first identify what PHP is waiting for. The wait may be for PhantomJS to finish, a shell wrapper or child process to close inherited output handles, a full pipe that PHP is not draining, or a page/resource operation inside PhantomJS that never completes. Logging the exact command, separating stdout and stderr, and inspecting the process tree usually narrows the cause.
For a controlled synchronous call, prefer proc_open() with an argument array on PHP 7.4 or newer. It starts the executable without a shell, gives you explicit stdout and stderr handling, and lets you inspect or signal the process. This does not fix a PhantomJS script that is still waiting on a page load; diagnose that separately.
1. Establish which process is still running
Before changing the PHP API, record enough information to reproduce the same launch conditions:

- PHP version and operating system.
- PhantomJS version, executable path, script path, and complete argument list.
- Current working directory and the account running PHP.
- Whether the caller is PHP CLI, PHP-FPM, Apache, or a Windows service.
- Separate stdout and stderr output, plus a timestamp for launch and completion.
Run the exact command manually under the same OS account and working directory as the PHP process. A command that works in an interactive terminal can still fail under FPM or a service because its PATH, permissions, environment, or working directory differs.
While the request is waiting, inspect the process tree with the tools available on your operating system. On Linux or macOS, a process-listing utility can show whether PHP has a shell child and whether PhantomJS remains below it. On Windows, use the process inspection tools available for the deployed version. These commands and signal semantics differ by platform, so treat them as observations, not portable recipes.
- If PhantomJS has exited but PHP has not returned, check whether a wrapper or descendant still holds inherited output descriptors open.
- If PhantomJS is still active and logs or network activity continue, investigate the PhantomJS script and its page/resource waits.
- If output stops and a pipe is involved, check whether the child could be blocked writing to a full pipe that PHP has not read.
These are diagnostic inferences from process relationships and stream behavior. A process listing alone does not prove the root cause; compare it with timestamps and captured output.
2. Understand what the PHP call waits for
shell_exec() returns the complete output of a command as a string, or null if an error occurs or the command produces no output. It is a synchronous interface: in the ordinary foreground case, PHP waits for the command to complete before continuing. The same general issue applies to other execution functions when used synchronously.
The PHP exec() manual documents a background-process caveat: “If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.” This describes the output handling needed for a process intended to continue in the background. It is not a universal cure for a foreground process that is meant to finish before PHP proceeds.
A shell can sit between PHP and PhantomJS when the command is passed as a string. Signaling the shell does not necessarily stop a child it started. PHP bug report #39992 describes this wrapper/child complication historically; it is a useful model, not a guarantee that every current platform behaves identically.
3. Replace a string command with proc_open
PHP 7.4.0 and newer accept an argument array in proc_open(). In this form PHP starts the process directly without going through a shell and handles argument escaping. This avoids many shell quoting surprises and gives PHP a process handle and explicit descriptors.
The following synchronous example captures stdout and stderr to separate files, rather than keeping pipes open. Set the paths for your installation. Ensure the PHP worker can execute PhantomJS and write to the log directory.
<?php
$phantom = '/usr/local/bin/phantomjs';
$script = '/srv/app/capture.js';
$url = 'https://example.com/';
$stdoutFile = '/var/log/myapp/phantom.stdout.log';
$stderrFile = '/var/log/myapp/phantom.stderr.log';
$command = [$phantom, $script, $url];
$descriptors = [
0 => ['file', '/dev/null', 'r'],
1 => ['file', $stdoutFile, 'a'],
2 => ['file', $stderrFile, 'a'],
];
$options = [];
$cwd = '/srv/app';
$env = null;
$process = proc_open($command, $descriptors, $pipes, $cwd, $env, $options);
if (!is_resource($process)) {
throw new RuntimeException('Could not start PhantomJS');
}
$exitCode = proc_close($process);
if ($exitCode !== 0) {
error_log("PhantomJS exited with status {$exitCode}; inspect its logs");
}
The descriptor specification routes stdin from /dev/null and appends the two output streams to files. On Windows, replace /dev/null with an appropriate input source or configure stdin according to that environment. The code intentionally waits for completion: it controls how the process is started and where output goes, but it does not impose a time limit.
If PhantomJS output is small and you want it in PHP memory, use pipes and read them correctly. Do not read stdout to completion and only then read stderr if the child might write enough stderr to fill its pipe; the child can block before closing stdout. Drain both streams, use a nonblocking/select-based design appropriate to the OS, or route them to files. Close pipe handles after consuming output, then call proc_close().
The PHP manual says proc_close() waits for process termination and closes open pipes to avoid deadlock, because the child may be unable to exit while pipes remain open. Closing them is not a substitute for reading output that the child must successfully write; plan stream handling from the outset.
Use pipes when you need the output in PHP
<?php
$command = ['/usr/local/bin/phantomjs', '/srv/app/capture.js', 'https://example.com/'];
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($command, $descriptors, $pipes, '/srv/app');
if (!is_resource($process)) {
throw new RuntimeException('Could not start PhantomJS');
}
fclose($pipes[0]);
// Suitable only when output is known to be small. For potentially large output,
// drain stdout and stderr concurrently or route them to files.
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
error_log("PhantomJS status {$exitCode}; stderr: {$stderr}");
}
This short pipe example is appropriate only when the output volume is bounded and small enough that sequential reading cannot fill the other pipe. For larger output, use concurrent draining or file descriptors. PHP changed proc_close() in PHP 8.3.0 so it returns the correct exit code even if proc_get_status() was called first. On older PHP versions, that call sequence could result in -1; check the installed version before interpreting status.
4. Check PhantomJS completion and page waits
PHP may be waiting correctly because the PhantomJS script has not finished. Review every success and error path in the script and make sure each path has a clear completion action and meaningful status. The PhantomJS API includes phantom.exit(), but its API index does not promise that adding it automatically fixes a PHP-side wait. The call must actually be reached; a callback that never fires still leaves the process busy.

Inspect page loading and resource logic. An archived PhantomJS issue report describes a case where PhantomJS 2.1.1 intermittently waited on a resource load. That is an anecdotal report, not evidence that every hang has the same cause. If the process remains active, add script-level timestamps around navigation, callbacks, resource waits, and exit paths. Avoid waiting indefinitely for a resource or event without a fallback.
5. Decide whether and how to cancel
proc_terminate() sends a signal to the process represented by the proc_open() handle and returns immediately. Use proc_get_status() to check whether that process has exited if you need confirmation. A string command may represent a shell wrapper, so terminating that handle may leave the PhantomJS child running.
For deployments that need cancellation, design a timeout policy around the actual process tree and operating system. PHP 7.4 added the create_process_group option for proc_open(); Windows has a documented bypass_shell option. These features and the behavior of process groups vary across environments. Validate cleanup on the target OS and service manager rather than copying a POSIX signal example into Windows code.
Do not silently discard the exit status when cancellation occurs. Record launch time, timeout time, termination attempt, final status, and relevant stderr. That record helps distinguish an expected timeout from a launch failure or a script that completed with an error.
6. Troubleshooting common symptoms
| Symptom | Likely cause | What to check or change |
|---|---|---|
| PHP never returns; PhantomJS is still active | PhantomJS is waiting on navigation, a resource, or script logic | Log page callbacks and resource activity; add a bounded page wait and ensure success/error paths reach the script’s exit logic. |
| PHP waits after PhantomJS disappears | A shell wrapper or descendant remains, or a process still owns an inherited stream | Inspect the process tree and open descriptors; prefer an argument-array command with proc_open() on PHP 7.4+ and route streams deliberately. |
| Child process stops producing output and appears stuck | A pipe may be full because PHP is not draining that stream | Drain stdout and stderr concurrently, or write them to files; close handles when done. |
| Command works in terminal but not web request | Different user, PATH, permissions, environment, or working directory | Use absolute executable/script paths, set the working directory, and verify access as the PHP service account. |
| Arguments with spaces or punctuation are misread | Shell quoting or interpolation changed the command | Use proc_open() with an argument array; validate values and avoid building a shell command from user input. |
Exit status is -1 after status polling |
Older PHP behavior when proc_get_status() precedes proc_close() |
Check the PHP version; PHP 8.3 corrected the exit-code behavior. Keep logs even when the code is unavailable. |
| Process termination leaves PhantomJS running | The handle may refer to a shell wrapper, or descendants may survive | Launch the executable directly where supported; use OS-appropriate process-tree cleanup and verify all descendants exit. |
| Blank output or no screenshot, but process completes | Page load failed, a bot check appeared, or the script saved no artifact | Inspect stderr, page status, output path and file permissions, and distinguish an empty result from a successful capture. |
7. Performance, reliability, and maintenance
There is no basis here to claim that changing from shell_exec() to proc_open() makes PhantomJS faster. The practical gains are control over arguments, streams, status, and process observation. Measure launch time and page work separately if performance matters, and avoid retaining large output strings when files or bounded logs will do.
For reliability, give each invocation a clear working directory, absolute paths, explicit stream destinations, and a recorded exit status. Bound page/resource waits in the PhantomJS script and have the PHP caller enforce its own request or job deadline. If screenshots run from a web request, consider whether that request can safely wait for the entire capture; a queued job may fit longer tasks better, but it also needs observable status and cleanup.
PhantomJS development is suspended and its repository is archived read-only. The repository identifies 2.1 as its latest stable release. That is relevant maintenance context when deciding how much effort to invest in a legacy capture path, but it does not by itself establish that a migration is required. Evaluate any replacement against your pages, required rendering behavior, deployment constraints, and ongoing support needs.
Or skip the browser setup
If the goal is to get a page image or PDF rather than maintain a local PhantomJS process, ScreenshotNeo provides a website screenshot API and MCP server. Its one-call API handles the browser setup. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; the response identifies page verdict and billing status in headers. An MCP server lets AI agents using Claude, Cursor, or another MCP client take screenshots. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
See the ScreenshotNeo API documentation for options and request details.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Sign up for 1,000 free screenshots a month with no card.
FAQ
Does shell_exec always hang with PhantomJS?
No. It waits for the foreground command to finish. A long wait may mean PhantomJS is still working, an output stream remains open, or a wrapper/descendant is still alive.
Will redirecting output always fix the hang?
No. It can matter for background launches and can keep large output from filling pipes, but it will not make a PhantomJS page callback complete or stop an unrelated descendant from running.
Should I add phantom.exit()?
Make sure the script reaches an exit path after success or failure, but adding the call alone cannot resolve a callback or resource wait that never completes.
Is PhantomJS still maintained?
The project repository says development is suspended and is archived read-only. Check its repository status before making a maintenance decision.


