Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To display a PhantomJS image in a PHP webpage, save the render somewhere your web server can serve, then use its browser-facing URL in an HTML <img> element. A server filesystem path such as /var/www/site/public/images/capture.png is not itself a URL. For images that should remain private, serve the bytes through a PHP endpoint that checks access and sends the correct image content type.
How the render becomes a browser image
There are two separate steps: PhantomJS writes image bytes to a file on the server, and the visitor’s browser requests those bytes through an HTTP URL. PHP can generate the page containing the image reference, but the browser—not PHP—loads an ordinary <img> source.
PhantomJS documents page.render as rendering a page to an image buffer and saving it as the specified filename. The filename extension normally determines the output format. See the PhantomJS render API and its screen-capture guide.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
In the examples below, the server-side file path is where PhantomJS writes; the URL path is what a browser requests. Your web server configuration must map the latter to the former.
#1 Best Overall
Render a file with PhantomJS
This PhantomJS script opens a page, checks the load status, and writes a PNG only on success:
var page = require('webpage').create();
page.open('https://example.com/', function (status) {
if (status === 'success') {
page.render('/path/to/public/images/capture.png');
}
phantom.exit();
});
Replace the URL with the page to capture and the filename with an absolute or otherwise valid server path in a directory intended for output. The example assumes that /path/to/public/images/ exists and is writable by the user running PhantomJS. It does not create the directory. The capture is saved only when the page open callback reports success; a failed load therefore needs separate handling if your application must report or retry it.
Use a filename extension that matches the intended image format. The render API lists PDF, PNG, JPEG, BMP, and PPM; GIF support depends on the Qt build. For common webpage images, PNG or JPEG are the straightforward choices. Do not use a filesystem path in the eventual HTML src.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Choose how PHP exposes the image
| Pattern | Use it when | Trade-off |
|---|---|---|
| Direct static image URL | The image is public and can live beneath a web-served directory. | Simple: the web server serves the file directly. The URL-to-directory mapping must be correct. |
| PHP image endpoint | The file is outside the public web root, access must be checked, or the file is selected dynamically. | PHP must validate the requested identifier, choose an allowed file, send headers, and stream the bytes. |
Option 1: Use a direct static URL
Put the output file under a public directory, for example public/images/capture.png, and use the URL that maps to it:
Rank #2
<img src="/images/capture.png" alt="Screenshot of the rendered page">
The browser requests /images/capture.png; the server maps that request to the corresponding file beneath its document root. A path such as /var/www/site/public/images/capture.png is a server path and should not be substituted into src unless that exact string is intentionally a valid URL in your setup.
For generated files, use a predictable filename only if overwriting it is intended. If each capture must be retained, generate or assign a unique filename and store the filename with the relevant application record so PHP can output the correct URL. Keep private or access-controlled captures out of a publicly served directory.
Option 2: Stream a private image through PHP
When the file is not publicly addressable, PHP can check that the chosen file exists and is readable, send an image MIME type, and stream it with readfile():
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11<?php
$file = __DIR__ . '/private-images/capture.png';
if (!is_file($file) || !is_readable($file)) {
http_response_code(404);
exit;
}
header('Content-Type: image/png');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>
Save this as a standalone endpoint, for example image.php, and reference it from the page:
<img src="/image.php" alt="Screenshot of the rendered page">
The example uses a fixed file. In a real application, perform the user’s authorization check before streaming and map a validated record identifier to a known server-side filename. Never concatenate an unchecked query-string value into a filesystem path. Otherwise a request intended to select an image can expose files outside the allowed image directory.
PHP’s header() manual notes that headers must be sent before output. Its readfile() manual documents reading a file and writing it to the output buffer. Avoid including a page template, debug text, or whitespace before the headers and binary data.
Save image bytes with PHP when needed
If PHP receives image bytes from a renderer or service rather than having PhantomJS write directly to the final location, file_put_contents() can save the byte string. It is binary-safe, creates a missing file, and overwrites an existing file by default. Check its return value instead of assuming the write worked:
<?php
$bytes = $imageBytes; // Binary image data supplied by your rendering step.
$path = __DIR__ . '/public/images/capture.png';
$written = file_put_contents($path, $bytes);
if ($written === false || $written !== strlen($bytes)) {
throw new RuntimeException('Could not write the complete image file.');
}
?>
$imageBytes must contain the actual binary response, not an HTML error page or a textual URL. Ensure the destination directory exists and is writable. The PHP file_put_contents() manual describes its return value as the number of bytes written or false.
Rank #4
Verify the complete path from render to page
- Run the render. Confirm the page load succeeded before calling
page.render, as in the PhantomJS screen-capture example: https://phantomjs.org/screen-capture.html. - Check the output file. Confirm the expected filename exists, has nonzero size, and is readable by the web server if PHP or the server must serve it.
- Check the path mapping. For a public file, identify the document root and the URL path it serves. For a private file, confirm the PHP endpoint points to the intended server path.
- Test the image response directly. Open the image URL in a browser. It should return image bytes, not an HTML error page or PHP warning. For a PHP endpoint, confirm the response uses the matching MIME type.
- Embed it in the page. Add an
<img>element with the URL insrcand a usefulaltdescription.
Troubleshoot broken or incorrect images
- Broken image icon: Open the
srcURL directly. Check its HTTP response and verify that the URL maps to the generated file, including the correct filename and case. - Works from the command line but not on the webpage: Compare the PhantomJS output directory, the web server’s document root, and the URL path. A server filesystem path does not automatically have a browser-visible URL.
- No file after a capture attempt: Check the page-open status, output filename, directory existence, and write permission for the PhantomJS process. The example renders only on a successful load.
- PHP write failed or produced a short file: Check that the destination directory exists and that PHP can write there. Test
file_put_contents()forfalseand compare its byte count with the expected input length; see the PHP manual. - Endpoint shows text, downloads unexpectedly, or appears corrupted: Match the
Content-Typeheader to the file format and ensure no output precedes the headers or image bytes. For PNG useimage/png; for JPEG useimage/jpeg. See PHP’s header documentation. - PNG/JPEG mismatch: Ensure the render filename extension and endpoint MIME type agree. PhantomJS normally infers the format from the filename extension: render API.
- Private endpoint exposes the wrong file: Replace arbitrary path input with an authorization check and a lookup from a validated identifier to an allowed server-side file.
Legacy-runtime and operational considerations
The PhantomJS documentation used for the render behavior is legacy documentation; current maintenance and compatibility with present-day systems are not established here. Before adopting PhantomJS in a new deployment, separately verify that its runtime is compatible with your operating system, dependencies, and security requirements. The PHP functions described here are documented by PHP, but actual paths, permissions, and web-server mappings depend on your deployment.
Keep image storage and delivery aligned with sensitivity. Public static files are usually the least complicated delivery route and allow the web server to serve the asset without running PHP for each request. An endpoint adds application-level access control and dynamic selection, but every request depends on correct authorization, path mapping, headers, and PHP execution. For either approach, plan how files are named, how long they remain stored, and whether a new render intentionally replaces an existing file.
Or skip the browser setup
If you need a screenshot endpoint rather than maintaining a PhantomJS render-and-file pipeline, ScreenshotNeo returns an image or PDF from one GET request. Its documented API options include PNG, JPEG or WebP output, full-page capture, and element capture by CSS selector. Read the API documentation for parameters and response behavior.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response indicates the page verdict and billing status in headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI agents using Claude, Cursor, or another MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo’s free plan and get 1,000 screenshots a month with no card.
Frequently Asked Questions
Does the PHP page need to run PhantomJS every time the image is viewed?
No. Once the render is saved, the browser can load that file from its URL; a PHP endpoint is needed only if you choose it for access control or dynamic delivery.
Can I use a filesystem path directly in an image’s src attribute?
No. The browser needs a URL it can request. Use a public URL mapped to the file or a PHP endpoint that streams it.
Which PhantomJS output format should I use?
PNG and JPEG are common choices for webpage captures. Match the filename extension and, for a PHP endpoint, the response Content-Type.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

