0

I want to get latitude and longitude of the guest and save them to a text file..

I used this:

<html>
<body>

<?php

 $location = print '
   <SCRIPT LANGUAGE="JavaScript">
window.onload=function(){
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(pos){
document.write("Location: "+pos.coords.latitude+","+pos.coords.longitude);
</script>
'

;



$Seb = "*******************" ;
 $file = "save.txt";
 $a = fopen($file, "a");
 fwrite($a,$location."\r\n");
    fwrite($a,$Seb."\r\n");
 fclose($a);


?>
<form action="index.php">
<input type="submit" value="Refresh">
</form>


</body>
</html>

but the result in the text file is :

1

with out any geolocation data

Any Help please?

1 Answer 1

1

This is totally not how it works. As javascript is client-side, and PHP is server-side, you can't just do it the way you are trying to. You need to send that information to the server from client browser. The most common way, would be using ajax to POST javascript generatred content...

With jQuery it would be as easy as:

In html file...

<script>
window.onload=function(){
if(navigator.geolocation)
{
  navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
  alert("Geolocation is not supported by this browser.");
}
}
function showPosition(pos){
   $.post('saver.php',{'lat':pos.coords.latitude,'lng':pos.coords.longitude},function(res){
      console.log(res);
   });
}
</script>

In saver.php

<?php
   print_r($_POST);
   $a = fopen("save.txt", "a");
   fwrite($a,"Location: $_POST[lat],$_POST[lng]\n*******************\n");
   fclose($a);
?>

PS. If you can't or don't want to use jQuery, please check this answer for information on how to use ajax in raw javascript.

Sign up to request clarification or add additional context in comments.

2 Comments

i am total noob with this but i just run this code and it doesn't save anything. what do i have to do in order to create the safe.txt ?
First, you should check if your browser does support geolocation. Second, if it is on. Third, if it sends proper request to saver.php. If it does, the only thing left would be write permissions for PHP script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.