ProxySimplePHP5
Jump to navigation
Jump to search
User:Kgolding extended the ProxySimplePHP code.
I have changed it to remove the need for the curl extension. Have also included retrying to fetch a tile after a failure, and to make use of a directory struct to store the tiles.
tiles.php:
1 <?php
2 /* Original source https://wiki.openstreetmap.org/wiki/ProxySimplePHP
3 * Modified to use directory structure matching the OSM urls and retries on a failure
4 */
5
6 $ttl = 86400; //cache timeout in seconds
7
8 $x = intval($_GET['x']);
9 $y = intval($_GET['y']);
10 $z = intval($_GET['z']);
11 if (isset($_GET['r'])) {
12 $r = strip_tags($_GET['r']);
13 } else {
14 $r = 'mapnik';
15 }
16
17 switch ($r) {
18 case 'mapnik':
19 $r = 'mapnik';
20 break;
21
22 case 'osma':
23 default:
24 $r = 'osma';
25 break;
26 }
27
28 $file = "tiles/$r/$z/$x/$y.png";
29 $img = null;
30 $tries = 0;
31 if (!is_file($file) || filemtime($file) < time()-(86400*30)) {
32 do {
33 $server = array();
34 switch ($r) {
35 case 'mapnik':
36 $server[] = 'a.tile.openstreetmap.org';
37 $server[] = 'b.tile.openstreetmap.org';
38 $server[] = 'c.tile.openstreetmap.org';
39
40 $url = 'http://'.$server[array_rand($server)];
41 $url .= "/".$z."/".$x."/".$y.".png";
42 break;
43
44 case 'osma':
45 default:
46 $server[] = 'a.tah.openstreetmap.org';
47 $server[] = 'b.tah.openstreetmap.org';
48 $server[] = 'c.tah.openstreetmap.org';
49
50 $url = 'http://'.$server[array_rand($server)].'/Tiles/tile.php';
51 $url .= "/".$z."/".$x."/".$y.".png";
52 break;
53 }
54
55 @mkdir(dirname($file), 0755, true);
56
57 $opts = array('http'=>array('header' => "User-Agent:TileProxy/1.0\r\n"));
58 $context = stream_context_create($opts);
59 $img = file_get_contents($url,false,$context);
60
61 if ($img) {
62 $fp = fopen($file, "w");
63 fwrite($fp, $img);
64 fclose($fp);
65 }
66
67 if ($tries++ > 5) exit(); // Give up after five tries
68 } while (!$img); // If curl has returned a broken file, then try downloading again
69 } else {
70 $img = file_get_contents($file);
71 }
72
73 $exp_gmt = gmdate("D, d M Y H:i:s", time() + $ttl * 60) ." GMT";
74 $mod_gmt = gmdate("D, d M Y H:i:s", filemtime($file)) ." GMT";
75 header("Expires: " . $exp_gmt);
76 header("Last-Modified: " . $mod_gmt);
77 header("Cache-Control: public, max-age=" . $ttl * 60);
78 // for MSIE 5
79 header("Cache-Control: pre-check=" . $ttl * 60, FALSE);
80 header ('Content-Type: image/png');
81 //readfile($file);
82 echo $img;
Usage instructions are as per ProxySimplePHP except you do not need to make the tiles directory.