ScreenshotNeo

BlogHow-to

How to Fix PHP Wkhtmltoimage Failures with Shell_exec

Diagnose wkhtmltoimage failures in PHP: capture exit codes and stderr, fix paths and permissions, handle runtime libraries, and secure rendering.

By the ScreenshotNeo team30 September 20268 min read

How to Fix PHP Wkhtmltoimage Failures with Shell_exec

Short answer: shell_exec() is a poor diagnostic tool for wkhtmltoimage. It returns the child process output, but not its exit status; null can mean either that execution failed or that the command produced no output. Use exec() (or a process wrapper), call the renderer by its absolute path, capture standard error, and test the same command as the PHP service account.

This guide walks through a repeatable fix for “nothing returned”, “command not found”, permission errors, missing libraries, blank images, and deployment-specific failures. It also covers safe command construction and a hosted alternative at the end.

1. Confirm what PHP is actually running

Before changing permissions or reinstalling binaries, record the execution context. A terminal session and a web request commonly use different users, environment variables, working directories and PATH values.

  • PHP SAPI (FPM, Apache module, CLI or another worker).
  • Operating system and version, including whether the system uses musl (such as Alpine) or glibc.
  • PHP version and renderer version.
  • Exact executable path and output path.
  • Arguments, with secrets removed.
  • Exit status, stdout and stderr.

Print this information to a private log, not to an untrusted browser response:

<?php
error_log(json_encode([
    'sapi' => PHP_SAPI,
    'php' => PHP_VERSION,
    'path' => getenv('PATH'),
    'cwd' => getcwd(),
    'user' => function_exists('posix_geteuid') ? posix_geteuid() : null,
], JSON_THROW_ON_ERROR));

2. Replace shell_exec() while diagnosing

The PHP manual says that execution failures cannot be detected with shell_exec() and recommends exec() when the program exit code is required. See the PHP shell_exec() documentation.

Capture the exit status and stderr instead of treating an empty shell_exec result as the diagnosis.
Capture the exit status and stderr instead of treating an empty shell_exec result as the diagnosis.
<?php
$binary = '/usr/local/bin/wkhtmltoimage';
$input = '/srv/app/render/input.html';
$output = '/srv/app/render/output.png';

$command = sprintf(
    '%s --quiet %s %s 2>&1',
    escapeshellarg($binary),
    escapeshellarg($input),
    escapeshellarg($output)
);

$lines = [];
$status = 0;
exec($command, $lines, $status);
$diagnostics = implode("\n", $lines);

error_log(json_encode([
    'command' => $command,
    'status' => $status,
    'diagnostics' => $diagnostics,
    'output_exists' => is_file($output),
    'output_bytes' => is_file($output) ? filesize($output) : 0,
], JSON_THROW_ON_ERROR));

if ($status !== 0 || !is_file($output) || filesize($output) === 0) {
    throw new RuntimeException('wkhtmltoimage failed; see the private application log');
}

The 2>&1 redirection merges stderr into the captured lines for diagnosis. Remove it when you need stdout and stderr kept separate, or use a process library that exposes both streams. Never concatenate raw user input into the command.

3. Use an absolute binary path

“Works in my shell” often means the interactive shell has a different PATH. Configure the complete path in application settings and verify it exists:

<?php
$binary = '/usr/bin/wkhtmltoimage';
if (!is_file($binary) || !is_executable($binary)) {
    throw new RuntimeException("Renderer is missing or not executable: $binary");
}

The phpwkhtmltopdf wrapper documentation supports a full binary path and detailed errors. Treat the path and service-account environment as things to verify, not assumptions.

4. Check permissions without using 777

The PHP worker needs execute permission on the binary, search permission on every parent directory, read permission for the HTML and assets, and write permission for the destination directory.

# Run these as an administrator while inspecting the deployment
command -v wkhtmltoimage
ls -l /usr/bin/wkhtmltoimage
namei -l /srv/app/render/output.png
sudo -u www-data /usr/bin/wkhtmltoimage --version
sudo -u www-data sh -c 'test -r /srv/app/render/input.html && test -w /srv/app/render'

Replace www-data with the account used by your PHP-FPM or web service. Fix ownership or group membership on the specific directories involved. Do not apply broad permissions such as chmod 777.

5. Test a minimal local render

Separate renderer problems from application, network and template problems with a tiny file:

cat > /tmp/wkhtml-test.html <<'HTML'
<!doctype html>
<html><body><h1>Renderer test</h1></body></html>
HTML

sudo -u www-data /usr/bin/wkhtmltoimage \
  /tmp/wkhtml-test.html /tmp/wkhtml-test.png
echo "status=$?"
file /tmp/wkhtml-test.png

If this fails, investigate the binary, libraries, fonts, policy and permissions before debugging your application. If it succeeds, add one variable at a time: remote URLs, local images, JavaScript, custom fonts and your production output directory.

6. Check operating-system compatibility and runtime files

A renderer binary is not automatically portable between Linux distributions. The official project notes that generic binaries generally do not work on Alpine because Alpine uses musl rather than glibc, and recommends distribution-specific packages where available. The project’s downloads page identifies the 0.12.6 stable series and dates that statement to June 11, 2020; it is not proof that this is the newest or best-supported choice for your environment.

In containers, serverless functions and minimal images, include the required shared libraries, font packages and font configuration. Inspect missing dependencies with the platform’s tooling, for example:

ldd /usr/bin/wkhtmltoimage | grep 'not found'
fc-list | head

Install packages designed for the exact base distribution, or build the image from a supported distribution instead of copying a binary from another image.

7. Handle Windows and extension-specific setups

For the PHP wkhtmltox extension, the PHP requirements documentation says Windows users must make wkhtmltox.dll available through PATH. That requirement applies to the extension; launching the standalone wkhtmltoimage.exe has its own executable and DLL search rules. Log the absolute executable path and test it from the same account that runs PHP.

8. Diagnose common symptoms

Symptom Likely cause Fix
shell_exec() returns null No output, execution failure, disabled function or shell policy Use exec(), capture status and stderr, and check PHP configuration and logs.
“command not found” Web process has a different PATH Use the absolute path and verify it under the service account.
“Permission denied” Binary or parent directory is not executable/searchable; policy blocks execution Inspect with ls/namei, correct narrowly, and review service confinement.
Exit status is nonzero with missing-library text Incompatible distribution or incomplete image Use a distribution-specific package and install required shared libraries and fonts.
Zero-byte or absent output Destination is not writable, renderer crashed, or input failed Check status, stderr, destination permissions and whether the input file exists.
Blank page JavaScript not finished, blocked resources, authentication or a bot check Render a local fixture, then inspect network access, waits and authentication requirements.
Works from CLI but not HTTP Different user, PATH, environment, working directory or limits Run the minimal command as the PHP account and use absolute paths.

9. Make command construction safe

Use escapeshellarg() for every path or value that must reach a shell command. Prefer fixed option lists and generated temporary filenames. Validate URLs and do not let a request choose arbitrary executable paths, output directories or shell fragments.

<?php
$allowedOptions = ['--quiet'];
$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL);
if (!$url) {
    throw new InvalidArgumentException('Invalid URL');
}

// For untrusted HTML, prefer a renderer API that does not require shell interpolation.
// If a shell command is unavoidable, quote every argument separately.

10. Protect the renderer from untrusted HTML

The wkhtmltopdf project warns not to use wkhtmltopdf with unsanitized untrusted HTML because it can lead to complete server takeover. Sanitize user HTML and JavaScript, isolate the process, restrict filesystem and command access with an operating-system sandbox, and run it as a low-privilege account. The project’s AppArmor guidance explains confinement and why renderer-level local-file restrictions alone may not be sufficient against a binary vulnerability.

11. Build a reliable production wrapper

  • Generate a unique temporary input and output path.
  • Set a process timeout and kill stuck children.
  • Capture status, stdout and stderr in structured logs.
  • Check that the output exists, is non-empty and has the expected file type.
  • Delete temporary files in a finally block.
  • Queue long renders instead of holding a web request open.
  • Retry only transient failures; do not retry deterministic permission or syntax errors.

Keep logs free of cookies, authorization headers and private document contents. When opening a support issue, include renderer version, OS/version, PHP execution context, exact path and options, exit status, stderr and a minimal reproducible HTML/CSS/JavaScript case, as requested by the project’s support guidance.

12. Performance, reliability and cost considerations

Launching a process for every request has startup overhead. Reuse a queue, cap concurrency to available CPU and memory, and avoid loading unnecessary remote assets. Cache deterministic renders by a content hash when the page can safely be cached. Large pages, web fonts, JavaScript and full-page images increase memory and time; measure them in your own deployment rather than relying on an assumed benchmark.

A hosted capture service can remove common overlays before producing the image.
A hosted capture service can remove common overlays before producing the image.

For a self-hosted renderer, your costs include compute, storage, bandwidth, maintenance and incident handling. A hosted API can move those operational concerns out of the PHP process, but you should still set timeouts, validate the returned content type and handle non-success responses.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP or PDF, so PHP does not need a local wkhtmltoimage binary:

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)
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}`);

See the ScreenshotNeo API documentation for options. Cookie banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. Response headers identify the page verdict and whether the shot was billed. Its MCP server lets Claude, Cursor and other MCP clients take screenshots, inspect pages and capture PDFs. The free plan includes 1,000 screenshots each month with no card, and paid plans start at $5 for 3,000.

Create a free ScreenshotNeo account.

FAQ

Does an empty string prove wkhtmltoimage succeeded?

No. The command may have produced no stdout, or it may have failed. Check the exit status and output file.

Should I redirect stderr to stdout?

It is useful for temporary diagnostics. In production, prefer separate structured streams and keep diagnostics private.

Is Alpine Linux supported by every wkhtmltoimage binary?

No. The project warns that generic binaries generally do not work with Alpine’s musl environment. Use a compatible package or base image.

Can I solve permission errors with chmod 777?

Do not. Grant only the service account the specific execute, read and write permissions it needs.

What should accompany a bug report?

Renderer version, OS and version, PHP context, exact command with secrets removed, exit status, stderr and a minimal reproducible case.