Can't Save URL Parameters in HTTP Get Request PHP - php

I'm working with Arduino and its GSM Shield. This is a hardware device that allows me to make an HTTP GET request to any IP address or web URL.
So we build a PHP script that reads URL parameters, and submits that data to the database. It will be saving our Arduino data when it pings our server.
Right now, when I visit the URL with the parameters in my browser, it works great. Everything saves and can be accessed via DB. But when the Arduino makes the request or I ping the URL with cURL, the record doesn't get saved.
The response I get shows that it is loading the page and spitting back the expected HTML. Why is my PHP not reading these URL parameters and saving them?
I've looked into sessions, etc no luck.
Thanks in advance!!
EDIT:::
handle_data.php (parses parameters, saves them to DB)
<?php
// Setup our DB login info
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "arduino";
if (!empty($_GET['lat']) && !empty($_GET['lon'])) {
function getParameter($par, $default = null){
if (isset($_GET[$par]) && strlen($_GET[$par])) return $_GET[$par];
elseif (isset($_POST[$par]) && strlen($_POST[$par]))
return $_POST[$par];
else return $default;
}
$lat = getParameter("lat");
$lon = getParameter("lon");
$person = $lat.",".$lon.",".$time.",".$sat.",".$speed.",".$course."\n";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO gps_data (latitude, longitude)
VALUES (".$lat.", ".$lon.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
// close connection
$conn->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else {
};
?>
Here's the Arduino Code:
if(started) {
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("internet.wind", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//Read IP address.
gsm.SimpleWriteln("AT+CIFSR");
delay(5000);
//Read until serial buffer is empty.
gsm.WhileSimpleRead();
//TCP Client GET, send a GET request to the server and
//save the reply.
numdata=inet.httpGET("http://cd5d6640.ngrok.io", 80, "/handle_data.php?lat=44.87654&lon=-88.77373", msg, 50);
//Print the results.
Serial.println("\nNumber of data received:");
Serial.println(numdata);
Serial.println("\nData received:");
Serial.println(msg);
}
Note - We're developing on localhost with MAMP, using ngrok to tunnel to localhost:8888. It works fine when you visit the ngrok url in the browser, but not when we hit it with a request. The url included is irrelevant and not active.

Related

Passing JSON to PHP not working

I've been trying to get my python code to transfer SQL query data from client running python to web server running PHP, then input that data into a MySQL database.
The below is the python test code simulating a single row:
#!/usr/bin/python
import requests
import json
url = 'http://192.168.240.182/insert_from_json.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":5,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=dict(payload=json.dumps(payload)), headers=headers)
print response
The below is the PHP script on the server side:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload']
//$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}';
$payload_array = json_decode($payload_dump,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If I comment out $payload_dump and instead use $payload and run the script the row is added correctly. But when I call the python script on the client I get a "response 200" but the record was not added. Something either my JSON string in python isn't formatted correctly or I am not passing the value correctly.
1) What is the syntax/procedure on the python code that would allow me to see what has actually been received by the PHP code. (i.e. convert the "$payload_dump" variable contents to a string and send back to the python script?
2) How do I resolve the above code?
Your first problem is using json headers which you shouldn't use since you aren't sending a raw json:
your data look like
{payload = {'key1': 'value1',
'key2': 'value2' }
}
and a raw json data should be in the form:
{'key1': 'value1',
'key2': 'value2'}
So you need to remove the headers from the request
response = requests.post(url, data=dict(payload=json.dumps(payload)))
Second you need to fix that missing semicolon
$payload_dump = $_POST['payload']
to
$payload_dump = $_POST['payload'];
Better solution
You can send the json data directly using requests
response = requests.post(url, json=payload)
then grab it in php with
$payload_array = json_decode(file_get_contents('php://input'), true);

PHP can't connect to mysql

I just made my own wamp server on my computer to handle twitch donations for a friend. The friend has a program that I made using c# that connects to the my server and reads the database. This works fine, the program reads my database just fine and lists the entries. BUT I have made a php website to send the entry (a new donation) to the database but I receive a connection timed out error just seconds after I press the button... my mysql server is set to allow every user and host with the correct password. I used the same IP user and password as on the c# program!
I can't figure out why the damn php website hosted on one.com can't connect!!
this is my code:
<?php
if (!empty($_GET['act'])) {
$servername = "81.83.95.34";
$username = "root";
$password = "mypassword";
$dbname = "tbc";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("server failed: " . $conn->connect_error);
}
$sql = "INSERT INTO donations (donations)
VALUES ('1')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} else {
?>
can anyone help me?
thank you very much!

How to insert data into mysql using android device?

I am beginner in mysql database. I am trying to create an online database application in android. This is a user registration application. I have tested this app with emulator and it succesfully inserting the entered data into database. At the same time tested this app with a real android device and can't insert the data into the database. Is it possoble to do? How can I do this with the same offline server. I am using wampserver version 2.5. My php code given below
<?php
$servername = "localhost";
$username = "micro";
$password = "micro";
$dbname = "insert_user";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$name=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$flag['code']=0;
$sql = "INSERT INTO user(name,pass,email)VALUES('$name','$pass','$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
you need a REST api
try this tutorial, maybe help
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
You have to connect your real device with USB cable.
If you had connected with USB try to run your IP in a browser of the phone as well as in PC If it opens the wamp server then run the application. If not then click on wamp server's green icon below the screen go to apache and then open httpd.conf file and find(Deny for all) change it to allow for all.

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

PHP mysql connect to any remove server the post variables

if (!empty($_POST)) {
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$db = $_POST['db'];
echo '<pre>';
print_r($_POST);
$con = #mysqli_connect($host . ":3360", $user, $pass, $db);
// $con=#mysqli_connect('192.168.100.42','root','vertrigo','skates');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo 'connected';
}
#mysqli_close($con);
}
I'm using this script to access remote db server in local(basically i want to access local db server through live webiste), howewer, I'm getting an error:
Failed to connect to MySQL: Unknown MySQL server host
'192.168.100.42:3360' (11004)
Please help to get out from this.
192.168.100.42 looks like a local IP. You'd need to try to connect to your static public IP and then forward port 3306 in your router to the 192.168.100.42 machine.
That's not your only problem;
Just because $_POST is not empty, don't assume it has those array keys set and not empty. Syntax like
if(isset($_POST['user'] && !empty($_POST['user'])))
Is much better.
Also, never use $_POST on any database interaction without sanitisation, and never connect to a database with the root user.
I don't know your exact application, but it's impossibly insecure.

Categories