Search code examples
javascriptphphtmlformatgenerate

How to write a txt file by using php which variable is get from Javascript


I want to write a txt file which format from latitude, longitude become to latitude longitude

how can I achieve it?

html:

<form method = "post" name = "searchbar">
        <input type="text" name="search" id="SearchBar" placeholder="input a ip">
        <br>
        <button type="button" onclick="getLocation()">get ip</button>
        <button type="submit" name = "writeip" id="id_Writeip">submit</button>
    </form>

php:

    if(array_key_exists('writeip', $_POST)) {
        writeip();}

    function writeip(){
        $myfile = fopen("testing.txt", "w") or die("Unable to open file!");
        $txt = $_POST["search"];
        fwrite($myfile, $txt);
        fclose($myfile);}

script:

<script>
        function getLocation()
        {
                navigator.geolocation.getCurrentPosition(showPosition);
        }
        
        function showPosition(position)
        {   
            document.getElementById("SearchBar").value = position.coords.latitude + ", " + position.coords.longitude;
        }
</script>

Solution

  • If I understand correctly, you need to see if the value is posted as part of the form submitted. In that case it can be checked like this.

    if(isset($_POST['search'])) {
    
        // You also noted you want the cords on new lines.
        $search = $_POST["search"];
        $data = explode(", ", $search);
        $cords = implode("\n", $data);
    
        writeSearch($cords);
    }
    
    function writeSearch($data) {
    
        $myfile = fopen("testing.txt", "w") or die("Unable to open file!");        
        fwrite($myfile, $data);
        fclose($myfile);
    }
    

    In this case we check if the post contains the search value, and then call the writeSearch function. The value we checked is then written to the file.