0

I am a beginner in Ionic. I am trying to save my current location (ie. latitude and longitude) in php database. And I am failing to do so. This is a real-time project.

This is my php script

locationsave.php

<?php 
if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");

        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }


$mysql_host = "localhost";

$mysql_database = "locationtracker";

$mysql_user = "root";

$mysql_password = "";

// Create connection

$conn = new mysqli($mysql_host, $mysql_user, $mysql_password,$mysql_database);





if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

} 



$postdata = file_get_contents("php://input");

  if ($postdata != null) {
$request = json_decode($postdata); 


$lat = $request->latitude;
$lng = $request->longitude;




$sql = "INSERT INTO user_info (uLatitude,uLongitude) VALUES ('$lat','$lng')";

$result = $conn->query($sql);


$conn->close();
}else{
    echo ("Data received is null!");
}
?>

And this is my home.ts file!

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers,RequestOptions } from '@angular/http';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';


declare var google;

@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  @ViewChild("latitude") latitude;

  @ViewChild("longitude") longitude;


  constructor(public navCtrl: NavController, public geolocation: Geolocation, public http:Http) {
    this.loadMap();
  }


  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {

      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      //passsing values to db
      let latitude = position.coords.latitude;
      let longitude = position.coords.longitude;

      //to pass in db method
      this.saveLocationCoords(latitude,longitude);

      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);


    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: this.map.getCenter()
    });

    let content = "<h4>Information!</h4>";         

    this.addInfoWindow(marker, content);

    }, (err) => {
      console.log(err);
    });

  }

  addInfoWindow(marker, content){

    let infoWindow = new google.maps.InfoWindow({
      content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });

  }



  //db method
  saveLocationCoords(latitude,longitude){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    console.log("In the territory")

      let coordsData = JSON.stringify({ latitude: latitude, longitude: longitude });
    this.http.post('http://localhost:82/authapp/locationsave.php', 
    coordsData, {headers: headers})
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);
    });

  }

}

And how can I update current location after every 1 minute?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Sep 07 '18 at 16:57
  • Hi @AlexHowansky..Thanks! I shall definitely take a look at the sql injection perspective of my code, do you have solution to what problem I am facing? – shashank verma Sep 07 '18 at 17:01
  • what error are you encountering? is the process failing/crashing? is the db insertion inserting blanks? are you having trouble passing the lat/long information from the frontend to the backend? A little bit more depth on what the problem actually is would help – Javier Larroulet Sep 07 '18 at 18:17
  • @JavierLarroulet actually what data I am passing is inserting null in the db, I tried to print my lat long in console and it is fine, but somehwo the values are not getting passed to the script and maybe null value is being passed. I have no clue where i am going wrong! – shashank verma Sep 08 '18 at 04:56
  • Giving your code a closer look, I'd point out that your ts file is sending variables via POST, which is fine, but you're not reading the POST in your PHP code as `file_get_contents` is not a valid way to capture the POST input stream. As a proof of concept, try changing `$lat` and `$lng` to read the `$_POST` superglobal (you should sanitize the data but just for testing try `$lat = $_POST['latitude'];` and `$lng = $_POST['longitude'];` and see if that works – Javier Larroulet Sep 08 '18 at 06:34

0 Answers0