Puppeteer is headless, Node.js API, which can load a website in background and can do some activities. The cool thing is you can render any website in background mode and can do your own action. You can get the script follow and dom elements and can use it by your own needs. Also, you can take screenshot, test your browser extension etc.. I'm going to show how you can run Puppeteer from PHP. As you know PHP is a server side language. So, there is some tricks need to work puppeteer from PHP. I am going to create a PHP, Puppeteer bridge to get it done. So, let's get started..

So What is Puppeteer?

An official definition from puppeteer website - Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium. - by https://pptr.dev/

What can Puppeteer do?

There are some cool features that Puppeteer offers. You can create your own cool application with puppeteer features. Let's take a look at the most used features.

  • Generate screenshots and PDFs of pages.
  • Crawl a SPA (Single-Page Application) and generate pre-rendered content (i.e. “SSR” (Server-Side Rendering)).
  • Automate form submission, UI testing, keyboard input, etc.
  • Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.
  • Capture a timeline trace of your site to help diagnose performance issues.
  • Test Chrome Extensions.

Installation

You need composer to install the package I've created. Also, you can download it as zip from the https://github.com/tuhin18003/puppeteer-php-bridge to your local computer.

$ composer require tuhin18003/puppteer-php-bridge

After install the composer package go inside the jobs folder, then install the npm package

$ npm install

How to use

After completing the the installation now we can use it from our PHP script. Suppose, we want to take a screenshot when one of our PHP script run. We assume the file name is - screenshot.php. We need to use the namespace in our PHP file and we need to add the PHP script. Take a look at the following PHP code snippets.

use PuppetBridge\Capture;

try{
    $screenCapture = new Capture();
    $screenCapture->setImageType( 'png' );
    $screenCapture->setUrl( 'https://google.com' );
    $screenCapture->setTop(0);
    $screenCapture->setLeft(0);
    $screenCapture->setWidth( '600' );
    $screenCapture->setHeight( '600' );
    $screenCapture->save( 'images/testimg.png' ); // make sure images folder is writable

} catch (Exception $ex) {
    echo $ex->getMessage();
}

Now when we will run our code from the browser it will create a screenshot and store in images folder. Make sure the images folder is written permission.

That's all. We have successfully created out screenshot from our PHP script.

Reference