ScreenshotNeo

BlogHow-to

How to Fix PhantomJS Rendering When Executed from PHP

Diagnose PhantomJS failures from PHP with reproducible checks for paths, permissions, page loading, HTTPS, output files, and legacy runtime limits.

By the ScreenshotNeo team30 September 20269 min read

How to Fix PhantomJS Rendering When Executed from PHP

Direct answer: run PhantomJS with the same operating-system account and environment used by PHP, use an absolute path to the intended binary, and record the exact command, exit code, standard output, and standard error. Then separate process startup from page loading: instrument page.open, JavaScript errors, console messages, resource requests, and page.render. The symptom tells you which branch to investigate.

PhantomJS is archived legacy software. Its official documentation remains useful for maintaining an existing installation, but the project’s wiki marks the 2.x line deprecated and the GitHub repository was archived on May 30, 2023. If this is a new system or a production renderer, include a migration plan for a maintained browser engine after you isolate the immediate failure.

1. Reproduce the failure outside PHP

Start by proving whether the binary and script work independently of your web request.

  1. Find the binary that PHP should run: command -v phantomjs and readlink -f $(command -v phantomjs) on Linux.
  2. Record its version with the absolute path: /opt/phantomjs/bin/phantomjs --version.
  3. Run the render script from a terminal with an absolute script and output path.
  4. Run the same command as the web-server account (for example, the account configured for PHP-FPM or Apache), from the same container, service unit, or scheduled-job environment.
  5. Check that this account can read the script and libraries and write the destination directory.

The official quick start treats PhantomJS as a command-line tool. Its troubleshooting guide also warns that multiple installations can cause a different version to be invoked. An interactive shell may have a different PATH, working directory, proxy, locale, or permissions than PHP.

ABS=/opt/phantomjs/bin/phantomjs
SCRIPT=/srv/render/render.js
OUT=/srv/render/output/page.png

"$ABS" --version
"$ABS" "$SCRIPT" https://example.com "$OUT"
printf 'exit=%s\\n' "$?"
ls -l "$OUT"

2. Capture child-process evidence in PHP

Do not debug a hidden command. Capture the command safely, return code, stdout, and stderr, while keeping API keys and cookies out of logs. The following example uses PHP’s proc_open, but the same evidence is needed with exec, shell_exec, Symfony Process, or another process API. See the PHP manual entry for exec for the process-execution context.

Separate PHP process startup from page loading by recording the command, identity, exit code, stdout, and stderr.
Separate PHP process startup from page loading by recording the command, identity, exit code, stdout, and stderr.
<?php
$phantom = '/opt/phantomjs/bin/phantomjs';
$script  = '/srv/render/render.js';
$url     = 'https://example.com';
$output  = '/srv/render/output/page.png';

$command = implode(' ', array_map('escapeshellarg', [
    $phantom, $script, $url, $output
]));

$descriptorSpec = [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
];

$process = proc_open($command, $descriptorSpec, $pipes, '/srv/render');
if (!is_resource($process)) {
    throw new RuntimeException('PHP could not start PhantomJS');
}
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);

error_log(json_encode([
    'command' => $command,
    'exit_code' => $exitCode,
    'stdout' => $stdout,
    'stderr' => $stderr,
    'output_exists' => is_file($output),
    'output_readable' => is_readable($output),
]));

if ($exitCode !== 0 || !is_file($output)) {
    throw new RuntimeException('PhantomJS render failed');
}

Use a fixed executable path rather than relying on PHP’s PATH. Confirm that the PHP process can traverse every parent directory. A successful terminal run does not prove that the service account can execute the binary, load its shared libraries, read the JavaScript file, or create the output.

3. Instrument page loading before changing browser flags

A process can start correctly and still fail to load a page. The callback status from page.open distinguishes those cases. Always exit on success and failure; PhantomJS otherwise may keep the PHP request waiting.

var system = require('system');
var page = require('webpage').create();

if (system.args.length < 3) {
  console.error('usage: phantomjs render.js URL OUTPUT');
  phantom.exit(2);
}

var url = system.args[1];
var output = system.args[2];

page.onError = function (message, trace) {
  console.error('PAGE ERROR: ' + message);
  trace.forEach(function (item) {
    console.error('  at ' + item.file + ':' + item.line +
      (item['function'] ? ' in ' + item['function'] : ''));
  });
};

page.onConsoleMessage = function (message) {
  console.log('CONSOLE: ' + message);
};

page.onResourceRequested = function (request) {
  console.log('REQUEST: ' + request.url);
};

page.onResourceError = function (error) {
  console.error('RESOURCE ERROR: ' + error.url + ' [' + error.errorCode + '] ' + error.errorString);
};

page.open(url, function (status) {
  console.log('OPEN STATUS: ' + status);
  if (status !== 'success') {
    phantom.exit(3);
    return;
  }
  page.render(output);
  console.log('RENDERED: ' + output);
  phantom.exit(0);
});

The quick-start example follows the success-status and explicit-exit pattern. The troubleshooting documentation describes page errors, network diagnostics, SSL problems, proxy behavior, and SELinux checks. Console messages are not forwarded automatically, so page.onConsoleMessage is useful when a page’s own JavaScript explains a blank render.

4. Match the symptom to the likely cause

Symptom Likely boundary Next action
command not found, no child process, or empty output PHP invocation Use an absolute binary path; log return code and stderr; compare the PHP service account and PATH.
Permission denied Identity or host security Grant the service account execute/read access to the binary and libraries and write access to the output directory; inspect SELinux audit logs where enabled.
Terminal succeeds, PHP fails Environment mismatch Run as the web-server account in the same service/container; compare working directory, environment, proxy, certificates, and filesystem mounts.
HTTP succeeds, HTTPS fails TLS runtime Check SSL/OpenSSL libraries visible to the actual PhantomJS process. Do not assume a PHP TLS configuration changes PhantomJS.
Open status is not success Page/network load Log resource requests and errors; verify DNS, proxy, redirects, certificates, and whether the page needs JavaScript PhantomJS cannot execute.
Page opens but content is missing Page timing or JavaScript Capture console and page errors, wait for the required application state, and verify that asynchronous requests finish before rendering.
Output file is missing Output path or write access Use an absolute destination, create the directory beforehand, and test write access as the PHP account.
Image is transparent CSS/output semantics Inspect the page background. Transparency can be normal when the page does not set a background color.
Process hangs Missing exit or unfinished callback Call phantom.exit() on every success and failure path after asynchronous work completes.

5. Handle HTTPS, proxies, SELinux, and X-server errors conditionally

HTTPS and OpenSSL

If an HTTP URL renders but its HTTPS equivalent does not, inspect the SSL libraries and certificates available to PhantomJS. Capture the exact stderr from the service process. Reinstalling PHP’s OpenSSL extension does not necessarily repair the libraries loaded by a separate PhantomJS binary.

Windows proxy behavior

The official troubleshooting page documents a Windows default-proxy latency problem and gives --proxy-type=none as a workaround for that situation. Apply it only when the observed failure matches that proxy issue. A proxy switch will not fix a bad URL, JavaScript exception, or permission failure.

SELinux

SELinux policy can prevent PhantomJS from executing or accessing files even when Unix mode bits look correct. Check audit records for denials and adjust deployment policy according to your organization’s rules. Do not disable SELinux as a first diagnostic step.

“PhantomJS cannot connect to X server”

Check the version before installing Xvfb. The official FAQ says PhantomJS 1.4 and earlier required an X server, while 1.5 and later are pure headless and do not need X11/Xvfb. An old forum instruction to start a display is therefore not a universal fix. See the official FAQ.

6. Verify render output and format assumptions

page.render(filename) writes an image buffer, and the filename extension selects the format. The render API documents PDF, PNG, JPEG, BMP, and PPM; GIF support depends on the Qt build. Check the file type with a platform tool such as file output/page.png, and verify that the file is readable by the PHP process that will return or move it.

A transparent image can be a valid render. If the page sets no background color, transparency is expected; add page CSS or a controlled background only when that is the intended visual result. A zero-byte file, a missing file, or an unreadable file points back to the destination path, permissions, disk quota, or an interrupted process.

7. Reliability and performance practices

  • Use absolute paths for the executable, script, working directory, and output.
  • Set an application timeout around the child process so a stalled page cannot occupy a PHP worker forever.
  • Log a correlation ID, URL, PhantomJS version, exit code, load status, and output path. Redact authorization headers, cookies, and secrets.
  • Render only after the page state you need is available. Waiting blindly for a long fixed delay slows every request; waiting too little produces incomplete images.
  • Reuse a queue or worker model for high volume rather than starting unbounded browser processes inside web requests.
  • Keep output files in per-job names and clean them after delivery. Ensure concurrent requests cannot overwrite one another.
  • Measure the separate phases: process startup, page load, render, file I/O, and response transfer. This identifies whether optimization belongs in PHP, the page, or the host.

PhantomJS’s age affects JavaScript and web-platform compatibility. A page that depends on modern browser APIs may fail even when process execution and networking are healthy. Treat that as a renderer-capability issue and evaluate a maintained browser automation path that matches your target pages and deployment constraints.

8. Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. Cookie and consent banners are accepted and removed before capture, along with more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

A clean capture pipeline removes obstructive overlays before producing the image and reports whether the result is billable.
A clean capture pipeline removes obstructive overlays before producing the image and reports whether the result is billable.

See the ScreenshotNeo documentation for the complete option list. The API supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper size and page ranges, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture, usage data, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

curl -G "https://api.screenshotneo.com/v1/shot" \\
  -d access_key=YOUR_API_KEY \\
  --data-urlencode url=https://stripe.com \\
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is available on every plan. Create a free ScreenshotNeo account.

9. Migration planning for legacy PhantomJS systems

Once the immediate incident is understood, compare replacement options using five questions: can PHP launch the renderer under the service identity; does it support the browser and JavaScript behavior your pages require; what headless, display, OS, and container dependencies exist; which output formats and fidelity are needed; and how much maintenance and migration work will the change require? The archived status means security updates and modern web compatibility should be part of the decision, even if the current workaround restores renders.

FAQ

Why does PhantomJS work in my terminal but not in PHP?

Usually PHP runs as another account or with a different path, working directory, environment, proxy, certificate set, or filesystem access. Run the absolute command as the PHP service account and compare stderr and exit codes.

Should I install Xvfb?

Only after checking the version and seeing an X-server error. PhantomJS 1.5 and later are documented as pure headless; the X-server requirement applies to 1.4 and earlier.

Why is my screenshot blank when the process exits successfully?

Inspect page.open status, resource errors, page exceptions, console output, and asynchronous timing. A successful process launch does not mean the target page loaded or executed correctly.

Can a transparent PNG mean the render failed?

No. It can be valid output when the page has no background color. Confirm the file is non-empty and inspect the page’s CSS before changing process settings.

Is PhantomJS still maintained?

No. The repository is archived and the project documentation labels PhantomJS 2.x deprecated. Use the diagnostic steps for legacy maintenance and plan a supported renderer for ongoing production work.