Secure Graphs - Using Google Charts API over https using PHP and cURL

Currently a project I’m involved in at work requires a dashboard to show the current status of orders within our automated workflow so for part of this I decided to use the google charts API, then I reliased that Google didn’t offer charts over https.

However the problem is fairly simple to circumvent by caching the graph to a file and then loading the file over https from your own site, indeed an example has already been published here but that example uses functions disabled on many web hosts (including mine) : file_get_contents() and file_put_contents(). These functions can pose a security risk when enabled so I decided to use a similar solution but using cURL which is supported by most hosting providers.

Example Google Chart

The basic principal of this is to form the URL in the normal way then to save the graph as a file and load it as a normal <img>. In the other example I referred to caching is used, in my application the graph will change so regularly and the number of hits will be low that it’s not worth doing this.

This process centres on one function which saves the image:

function saveImage($chart_url,$local_image_path,$image_name)
{
    //initialize curl

    $ch = curl_init($chart_url);
    //open file to write image to

    $fp = fopen($local_image_path.$image_name, 'wb');

    // set URL and other appropriate options

    $options = array(CURLOPT_FILE => $fp,
                     CURLOPT_HEADER => 0,
                     CURLOPT_FOLLOWLOCATION => 1,
                         CURLOPT_TIMEOUT => 60);

    curl_setopt_array($ch, $options);
    //get the image

    curl_exec($ch);
    //close the connection

    curl_close($ch);
    //finish writing to the file

    fclose($fp);
}

This then leaves you with a png file in the path you specified (which you need write permissions on), this can then be inserted into your page using the normal methods.

This only works with the http chart API not the newer javascript based interactive graphs, if absolute privacy of your data is required then using the new API would be a better solution as no data is sent to the Google servers - the graph is generated using a javascript library locally , as long as the libraries are loaded securely there should be no complaints from any browser.