I am getting ready to migrate my data collection (using arduino Yun) from my local virtual server to a live website. Below are the two files I am using to post and receive data. There is no need for any human interaction with the data until after it is loaded into the data base. More than one device will be uploading data which why I thought to use the receiver.php file.
I wonder if someone would be willing to help educate me on a secure way to implement the below. I am not concerned with someone intercepting the data, just don't want someone messing with my database.
post.py (on the Arduino Yun)
#!/usr/bin/python
import sys
import sqlite3 as sqlite
import requests
import json
url = 'http://xxx.xxx.x.x/reciever.php'
headers = {'content-type': 'application/json'}
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite.connect('/mnt/sda1/sensor_flow.db')
con.row_factory = dict_factory
cur = con.cursor()
cur = con.execute("SELECT * FROM data_log")
recs = cur.fetchall()
data=dict(payload=json.dumps(recs))
#print data
con.commit()
con.close()
response = requests.post(url, data=dict(payload=json.dumps(recs)))
print response
Receiver.php (on the Server)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch ) WHERE date_time = 0;";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
If my code has problems could you explain why it is a problem as well?
Thank you advance for any and all help!