example php client
[phancap.git] / docs / php-client.php
1 <?php
2 /**
3  * Example phancap API client written in PHP.
4  * Mainly to demonstrate the authentication.
5  *
6  * @author Christian Weiske <cweiske@cweiske.de>
7  */
8
9 //phancap service configuration
10 $phancapConfig = array(
11     'url'    => 'http://example.org/phancap.phar/get.php',
12     'token'  => 'demo',
13     'secret' => 'coho8ajj2as'
14 );
15
16 //fetch the screenshot URL
17 $screenshotUrl = getScreenshotUrl('http://example.org/', $phancapConfig);
18
19 //output an image tag with the screenshot url
20 echo '<img src="' . htmlspecialchars($screenshotUrl) . '"'
21     . ' alt="Screenshot for example.org/" />' . "\n";
22
23 /**
24  * Creates an URL for a website screenshot.
25  * Automatically adds a authentication signature for phancap.
26  *
27  * @param string $websiteUrl    URL to website from which the screenshot
28  *                              shall be generated
29  * @param array  $phancapConfig Configuration array. Supported Keys:
30  *                              - url: Full URL to phancap's get.php
31  *                              - token: Username
32  *                              - secret: Password for the username
33  *
34  * @return string URL for the website screenshot
35  */
36 function getScreenshotUrl($websiteUrl, $phancapConfig)
37 {
38     //default parameters for the phancap service
39     $parameters = array(
40         'url' => $websiteUrl,
41         'swidth' => 300,
42         'sformat' => 'jpg',
43     );
44
45     if (isset($phancapConfig['token'])) {
46         $parameters['atoken']     = $phancapConfig['token'];
47         $parameters['atimestamp'] = time();
48
49         //create signature
50         ksort($parameters);
51         foreach ($parameters as $key => $value) {
52             $encparams[] = $key . '=' . rawurlencode($value);
53         }
54         $encstring = implode('&', $encparams);
55         $signature = hash_hmac('sha1', $encstring, $phancapConfig['secret']);
56         //append signature to parameters
57         $parameters['asignature'] = $signature;
58     }
59
60     //url-encode the parameters
61     $urlParams = array();
62     foreach ($parameters as $key => $value) {
63         $urlParams[] = $key . '=' . urlencode($value);
64     }
65
66     //final URL
67     return $phancapConfig['url'] . '?' . implode('&', $urlParams);
68 }
69 ?>