416
votes

Is there any way of taking a screenshot of a website in PHP, then saving it to a file?

25
If you like a drop in solution, have a look at Usersnap - it's a nice service offering accurate website screenshots. You just have to add a small Javascript snippet to your page to make it work.Gregor
Usersnap cant cope with webpages that use Ajax to generate the content like on this page. How could I achieve that? lets say: make the screenshot 10 seconds after initial loading of the page finishedrubo77
@rubo77: Usersnap supports such dynamic DOMs, I've tried it with your page - the screenshot reproduces the exact situtation including all positions.Gregor

25 Answers

286
votes

LAST EDIT: after 7 years I'm still getting upvotes for this answer, but I guess this one is now much more accurate.


Sure you can, but you'll need to render the page with something. If you really want to only use php, I suggest you HTMLTOPS, which renders the page and outputs it in a ps file (ghostscript), then, convert it in a .jpg, .png, .pdf.. can be little slower with complex pages (and don't support all the CSS).

Else, you can use wkhtmltopdf to output a html page in pdf, jpg, whatever.. Accept CSS2.0, use the webkit (safari's wrapper) to render the page.. so should be fine. You have to install it on your server, as well..

UPDATE Now, with new HTML5 and JS feature, is also possible to render the page into a canvas object using JavaScript. Here a nice library to do that: Html2Canvas and here is an implementation by the same author to get a feedback like G+. Once you have rendered the dom into the canvas, you can then send to the server via ajax and save it as a jpg.

EDIT: You can use the imagemagick tool for transforming pdf to png. My version of wkhtmltopdf does not support images. E.g. convert html.pdf -append html.png.

EDIT: This small shell script gives a simple / but working usage example on linux with php5-cli and the tools mentioned above.

EDIT: i noticed now that the wkhtmltopdf team is working on another project: wkhtmltoimage, that gives you the jpg directly

89
votes

Since PHP 5.2.2 it is possible, to capture a website with PHP solely!

imagegrabscreen — Captures the whole screen

<?php
$img = imagegrabscreen();
imagepng($img, 'screenshot.png');
?>

imagegrabwindow - Grabs a window or its client area using a windows handle (HWND property in COM instance)

<?php
$Browser = new COM('InternetExplorer.Application');
$Browserhandle = $Browser->HWND;
$Browser->Visible = true;
$Browser->Fullscreen = true;
$Browser->Navigate('http://www.stackoverflow.com');

while($Browser->Busy){
  com_message_pump(4000);
}

$img = imagegrabwindow($Browserhandle, 0);
$Browser->Quit();
imagepng($img, 'screenshot.png');
?>

Edit: Note, these functions are available on Windows systems ONLY!

58
votes

If you don't want to use any third party tools, I have come across to simple solution that is using Google Page Insight api.

Just need to call it's api with params screenshot=true.

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=https://stackoverflow.com/&key={your_api_key}&screenshot=true

For mobile site view pass &strategy=mobile in params,

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=http://stackoverflow.com/&key={your_api_key}&screenshot=true&strategy=mobile

DEMO.

19
votes

You can use simple headless browser like PhantomJS to grab the page.

Also you can use PhantomJS with PHP.

Check out this little php script that do this. Take a look here https://github.com/microweber/screen

And here is the API- http://screen.microweber.com/shot.php?url=https://stackguides.com/questions/757675/website-screenshots-using-php

18
votes

This ought to be good for you:

https://wkhtmltopdf.org/

Make sure you download the wkhtmltoimage distribution!

10
votes

Yes. You will need some things tho:

See khtmld(aemon) on *nx. See Url2Jpg for Windows but since it is dotNet app you should also chek Url2Bmp

Both are console tools that u can utilise from your web app to get the screenshot.

There are also web services that offer it. Check this out for example.

Edit:

This link is useful to.

10
votes

It's in Python, but going over the documentation and code you can see exactly how this is done. If you can run python, then it's a ready-made solution for you:

http://browsershots.org/

Note that everything can run on one machine for one platform, or one machine with virtual machines running the other platforms.

Free, open source, scroll to bottom of page for links to documentation, source code, and other information.

5
votes

Well, PhantomJS is a browser that can be easily put on a server and integrate it to php. You can find the code in WDudes. They have included lot more features like specifying the image size, cache, download as a file or display in img src etc.

<img src=”screenshot.php?url=google.com” />

URL Parameters

  • Width and Height: screenshot.php?url=google.com&w=1000&h=800

  • With cropping: screenshot.php?url=google.com&w=1000&h=800&clipw=800&cliph=600

  • Disable cache and load fresh screesnhot:
    screenshot.php?url=google.com&cache=0

  • To download the image: screenshot.php?url=google.com&download=true

You can see the tutorial here: Capture Screenshot of a Website using PHP without API

5
votes

There is a lot of options and they all have their pros and cons. Here is list of options ordered by implementation difficulty.

Option 1: Use an API (the easiest)

Pros

  • Execute Javascript
  • Near perfect rendering
  • Fast when caching options are correctly used
  • Scale is handled by the APIs
  • Precise timing, viewport, ...
  • Most of the time they offer a free plan

Cons

  • Not free if you plan to use them a lot

Option 2: Use one of the many available libraries

Pros

  • Conversion is quite fast most of the time

Cons

  • Bad rendering
  • Does not execute javascript
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)
  • Sometimes not so easy to install
  • Complicated to scale

Option 3: Use PhantomJs and maybe a wrapper library

Pros

  • Execute Javascript
  • Quite fast

Cons

  • Bad rendering
  • PhantomJs has been deprecated and is not maintained anymore.
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)
  • Complicated to scale
  • Not so easy to make it work if there is images to be loaded ...

Option 4: Use Chrome Headless and maybe a wrapper library

Pros

  • Execute Javascript
  • Near perfect rendering

Cons

  • Not so easy to have exactly the wanted result regarding:
    • page load timing
    • proxy integration
    • auto scrolling
    • ...
  • Complicated to scale
  • Quite slow and even slower if the html contains external links

Disclaimer: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.

4
votes

cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf

4
votes

I always use microweber screen to capture screenshot of any webpage. Here we can find a well written tutorial. This is easier and should not take more than 3 minutes to learn.

3
votes

I set up finally using microweber/screen as proposed by @boksiora.
Initially when trying the mentioned link here what I got:

Please download this script from here https://github.com/microweber/screen

I'm on Linux. So if you want to run it, you may adjust my step follow to your environment.
Here are the step I did on my shell on DOCUMENT_ROOT folder:

$ sudo wget https://github.com/microweber/screen/archive/master.zip
$ sudo unzip master.zip
$ sudo mv screen-master screen
$ sudo chmod +x screen/bin/phantomjs
$ sudo yum install fontconfig
$ sudo yum install freetype*
$ cd screen
$ sudo curl -sS https://getcomposer.org/installer | php
$ sudo php composer.phar update
$ cd ..
$ sudo chown -R apache screen
$ sudo chgrp -R www screen
$ sudo service httpd restart

Point your browser to screen/demo/shot.php?url=google.com. When you see the screenshot, you are done. Discussion for more advance setting is available here and here.

3
votes

There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc

The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.

I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.

Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.

// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots

// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');

// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';

// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'

// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />

For e.g. here's a full height screenshot of this very page:

https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/8f1666d1f4195b1cb84ffa5f992ee18992a2b35e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F757675%2Fwebsite-screenshots-using-php%2F43652083%2343652083&full_page=true

full page screenshot of stackoverflow.com question powered by urlbox.io

2
votes

I'm on Windows so I was able to use the imagegrabwindow function after reading the tip on here from stephan. I added in cropping (to get rid of the Browser header, scroll bars, etc.) and resizing to get a final image. Here's my code. Hope that helps someone.

1
votes

webkit2html works on Mac OS X and Linux, is quite simple to install and to use. See this tutorial.

For Windows, you can go with CutyCapt, which has similar functionality.

1
votes

I used bluga. The api allows you to take 100 snapshots a month without paying, but sometimes it uses more than 1 credit for a single page. I just finished upgrading a drupal module, Bluga WebThumbs to drupal 7 which allows you to print a thumbnail in a template or input filter.

The main advantage to using this api is that it allows you to specify browser dimensions in case you use adaptive css, so I am using it to get renderings for the mobile and tablet layout as well as the regular one.

There are api clients for the following languages:

PHP, Python, Ruby, Java, .Net C#, Perl and Bash (the shell script looks like it requires perl)

1
votes

It all depends on how you wish to take the screenshot.

You could do this via PHP, using a webservice to get the image for you

grabz.it has a webservice to do just this, here's an article showing a simple example of using the service.

http://www.phpbuilder.com/articles/news-reviews/miscellaneous/capture-screenshots-in-php-with-grabzit-120524022959.html

1
votes

I wrote a quick and dirty app the other day for doing this using Google API. Most certainly scope for improvement...

  • It uses the latest Google API ver 5.
  • Image size now 500px wide
  • Supports desktop & mobile view
  • Save to a file in a specified folder
  • Incorporate a rudimentary cache system

Find it here with a live demo and code.

I did not post the code here simply because I keep on refining it and hopefully when I have time, convert it into a proper class.

0
votes

I used page2images. It is developed base on the cutycapt which is really fast and stable. If you do not want to spend too much time on the performance and configuration, you should use it. If you go to their website, you can find more details and sample PHP code.

0
votes

You can use https://grabz.it solution.

It's got a PHP API which is very flexible and can be called in different ways such as from a cronjob or a PHP web page.

In order to implement it you will need to first get an app key and secret and download the (free) SDK.

And an example for implementation. First of all initialization:

include("GrabzItClient.class.php");

// Create the GrabzItClient class
// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
$grabzIt = new GrabzItClient("Sign in to view your Application Key", "Sign in to view your Application Secret");

And screenshoting example:

// To take a image screenshot
$grabzIt->URLToImage("http://www.google.com");  
// Or to take a PDF screenshot
$grabzIt->URLToPDF("http://www.google.com");
// Or to convert online videos into animated GIF's
$grabzIt->URLToAnimation("http://www.example.com/video.avi");
// Or to capture table(s)
$grabzIt->URLToTable("http://www.google.com");

Next is the saving.You can use one of the two save methods, Save if publicly accessible callback handle available and SaveTo if not. Check the documentation for details.

0
votes

After a lot for surfing on web I found this.

PPTRAAS > A free tool to capture screenshot by passing your URL as a parameter

They provide multiple options by simply hitting their URL.

  1. Get full page screenshot

    https://pptraas.com/screenshot?url={YOU URL HERE}

  2. Get page screenshot of specific size

    https://pptraas.com/screenshot?url={YOU URL HERE}&size=400,400

  3. One can even convert the page to pdf

    https://pptraas.com/pdf?url={YOU URL HERE}

0
votes

You could do 2 things.

Use Puppeteer

You can use the PHP Puppeteer package to spin up a browser and take a screenshot.

Use an API

There are a lot of screenshot APIs. You could look at ScreenshotAPI.net for example. (Disclaimer I'm the creator of that API)

-1
votes

Not directly. Software such as Selenium have features like this and can be controlled by PHP but have other dependencys (such as running their java-based server on the computer with the browser you want to screenshot)

-1
votes

you can use cutycapt .

kwhtml is deprecated and show page like old browser.

-1
votes

I've found this to be the best and easiest tool around: ScreenShotMachine. It's a paid service, but you get 100 free screenshots and you can buy another 2,000 for (about) $20, so it's a pretty good deal. It has a very simple usage, you just use a URL, so I wrote this little script to save a file based on it:

<?php
  $url = file_get_contents("http://api.screenshotmachine.com/?key={mykey}&url=https://stackoverflow.com&size=X");

  $file = fopen("snapshots/stack.jpg", "w+");
  fwrite($file, $url);
  fclose($file);
  die("saved file!");
?>

They have a very good documentation here, so you should definitely take a look.