Skip to content

Instantly share code, notes, and snippets.

@luigifab
Last active June 25, 2022 09:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luigifab/e89346ff43df53667e1c3fe791a7a519 to your computer and use it in GitHub Desktop.
Save luigifab/e89346ff43df53667e1c3fe791a7a519 to your computer and use it in GitHub Desktop.
OpenStreetMap and OpenTopoMap local cache
<?php
// configuration : https://www.visugpx.com/forum/read_13532.html
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('default_socket_timeout', 20);
//echo '<pre>'; print_r($_SERVER); exit;
$host = getenv('HTTP_HOST');
$tile = getenv('REQUEST_URI');
if (stripos($tile, 'test.png') !== false) {
exit('TileCache 1.4, PHP '.PHP_VERSION.', host: '.$host);
}
if (stripos($host, 'openstreetmap') !== false) {
$dir = 'osm'; // open street map
$ip = '151.101.122.217';
if ($host == 'tile.openstreetmap.org')
$host = 'a.tile.openstreetmap.org';
}
else if (stripos($host, 'opentopomap') !== false) {
$dir = 'otm'; // open topo map
$ip = '131.188.76.144';
if ($host == 'tile.opentopomap.org')
$host = 'a.tile.opentopomap.org';
}
else if (stripos($host, 'tile.thunder') !== false) {
$dir = 'ocm'; // open cycle map
$ip = '88.99.98.237';
}
else if (stripos($host, 'geo.admin.ch') !== false) {
$host = 'wmts1.geo.admin.ch';
$dir = 'stm'; // swiss topo map
$ip = '13.32.219.80';
}
else {
header('HTTP/1.1 404 Not Found');
exit('unknown host: '.$host);
}
$file = $dir.strtok($tile, '?');
if (is_file($file) && (filesize($file) < 500))
unlink($file);
if (!is_file($file)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
curl_setopt($ch, CURLOPT_RESOLVE, [$host.':443:'.$ip]);
curl_setopt($ch, CURLOPT_URL, getenv('REQUEST_SCHEME').'://'.$host.$tile);
curl_setopt($ch, CURLOPT_USERAGENT, getenv('HTTP_USER_AGENT'));
curl_setopt($ch, CURLOPT_REFERER, getenv('HTTP_REFERER'));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
curl_setopt($ch, CURLOPT_TIMEOUT, 8);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: */*',
'Accept-Language: en-us,en;q=0.5',
]);
$result = curl_exec($ch);
$result = (($result === false) || (curl_errno($ch) !== 0)) ? false : $result;
curl_close($ch);
if (empty($result)) {
header('HTTP/1.1 500 Internal Server Error');
var_dump($result);
exit;
}
else {
$dir = dirname($file);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
if (is_dir($dir)) {
file_put_contents($file, $result);
}
}
}
if (is_file($file)) {
header('Access-Control-Allow-Origin: *');
header('Content-Type: image/png');
echo file_get_contents($file);
}
else {
header('HTTP/1.1 404 Not Found');
echo '404';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment