Detect HTML5 Geolocation Support Using PHP
I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.
How to do this with 开发者_Python百科or without PHP.
Have you considered using Modernizr to detect the HTML5 support? This isn't PHP specific since it's done in JavaScript but you can use this snippet to load your backup file:
if (Modernizr.geolocation){
// Access using HTML5
navigator.geolocation.getCurrentPosition(function(position) { ... });
}else{
// Load backup file
var script = document.createElement('script');
script.src = '/path/to/your/script.js';
script.type = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}
(Based on http://www.modernizr.com/docs/#geolocation)
Without PHP:
http://fortuito.us/diveintohtml5/detect.html#geolocation
With PHP:
you have to check the browser version
http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php/
(note: http://apptools.com/phptools/browser/)
Well the only way to detect Geolocation is with the navigator, and used like so:
if(navigator.geolocation)
{
//Geo in Browser
}
So what I would personally do is create an Ajax request to server and do a redirect like so:
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
/*
* Send Position to server where you can store it in Session
*/
document.location = '/'; //Redirect and use the session data from above
}, function(message){
/*
* Send false to the server, and then refresh to remove the js geo check.
*/
});
}
on server side you would do something like so:
<?php /* session/geolocation.php */
//Require system files
include '../MasterBootloader.php';
/*
* Session is already started in the above inclustion
*/
if(!isset($_SESSION['geo']['checked']) && is_agax_request())
{
$_SESSION['geo'] = array();
if(isset($_GET['postition']))
{
$_SESSION['geo']['supported'] = true;
$_SESSION['geo']['location'] = json_decode($_REQUEST['geo_position']);
}
$_SESSION['geo']['checked'] = true;
}
?>
now when the javascript redirects you, in your index you can check to see if the exists before outputting your html, then you will know server side if GEO is supported!
You can check Geolocation support using javascript:
function supports_geolocation() {
return !!navigator.geolocation;
}
I've taken the function from the nice Dive into HTML 5.
You can use canisuse.js script to detect if your browsers supports geolocation or not
caniuse.geolocation()
精彩评论