Send data to a php webpage using electric imp - php

I am using a php website with electric imp. I am trying to send data from my electric imp to my website and retrieve the data on my website which I will later use as a variable.
Device code (electric imp)
function setLed(state) {
if(state == 1)
{
(led5 is pin5)
led5.write(state) ;
server.log("Light : " + state);
local code = 1 * 2 + state ; // 1 is pin number
server.log ("switch " + code ) ;
agent.send ( "swdata", code ) ;
}
Agent Code (electric imp)
// define the http handler
function requestHandler(request, response) {
local state = request.query["led"].tointeger() ;
device.send("led", state);
response.send(200, "OK");
log(state);
}
// register the http handler
http.onrequest(requestHandler);
function log (code) {
const url = "http://jnghgi.php";
local headers = { "Content-Type" : "application/json"} ;
local state = code % 2 ;
local pin = (code - state) / 2 ;
server.log ("state"+state+" pin"+pin) ;
local body = { "pin" : pin , "state" : state } ;
local jsonBody = http.jsonencode(body) ;
// POST the values
local request = http.post(url, headers, jsonBody);
local response = request.sendsync();
server.log(response.statuscode + ": " + response.body);
}
device.on("swdata", log) ;
php code to (website)
<?php
$jsonbody = file_get_contents('php://input') ;
dumping the $json body gives me an output of string(0) "" and dumping jsonobj gives a null. as far as I can tell the problem is occurring with the transfer of the data from the electric imp to the website
var_dump($jsonbody);
$jsonobj = json_decode($jsonbody) ;
var_dump($jsonobj);
$state = $jsonobj -> state ;
$pin = $jsonobj -> pin ;
$result = updatered($state, $pin) ;
//var_dump($result);
//var_dump($state);
function updatered(){
include ("db.php") ;
// connect to the database to get current state
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) { die("Connection failed: " . mysqli_connect_error());
echo "fail"; }
$sql = "UPDATE LED
SET LOn = $state
WHERE ID = $pin";
$result = mysqli_query($conn, $sql);
}
?>
on my website I have attempted to retrieve the data using a $_GET but that was unsuccessful, if anyone has any knowledge on how I could retrieve the data then help would be appreciated, thanks

The problem I was having was because I didn't pass $state and $pin through my parameters for my function:
function updatered($state, $pin)

Related

Arduino can't POST data to PHP

I have written a code for my Arduino to read data from sensor and then post to a PHP file called post-data.php, which then the PHP will insert the data into a database.
However, my Arduino does not seemed to be able to post the data or it is not posting it correctly.
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#endif
#define signalPin 12
#define sensorPin A0
const char *ssid = "****";
const char *password = "*****";
const char* serverName = "http://smartswitchfyp.rf.gd/post-data.php";
String apiKeyValue = "*******";
ESP8266WebServer server(80);
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
Serial.print("Configuring access point...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFI connected");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
void loop() {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
sensor();
// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
//String httpRequestData = "api_key=******9&value1=24.75&value2=49.54";
//Serial.print("httpRequestData: ");
//Serial.println(httpRequestData);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(response);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
delay(1000);
}
I have checked that my serverName is correct.
I have tested the post-data.php, and it works fine as there is an update at my database. Below is the test code, test.php I used to test post-data.php
<html>
<body>
<form action="post-data.php" method="post">
api: <input type="text" name="api_key">
Name: <input type="text" name="value1">
Email: <input type="text" name="value2">
<input type="submit">
</form>
</body>
</html>
And below is my post-data.php file
<?php
$servername = "sql101.epizy.com";
$dbname = "epiz_28338452_smartswitch";
$username = "epiz_28338452";
$password = "********";
// Keep this API Key value to be compatible with the ESP32 code provided in the project page. If you change this value, the ESP32 sketch needs to match
$api_key_value = "*******";
$api_key = $value1 = $value2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$api_key = test_input($_POST["api_key"]);
if($api_key == $api_key_value) {
$value1 = test_input($_POST["value1"]);
$value2 = test_input($_POST["value2"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Sensor (value1, value2) VALUES ('" . $value1 . "', '" . $value2 . "')";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else {
echo "Wrong API Key provided.";
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm 90% sure that is not the post-data.php file problem but my Arduino not able to post the data to the php file.
At my Arduino code, I used the line
http.begin(serverName);
to connect to the post-data.php and then prepare the header:
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
and prepare the content:
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
where current and power is process in other function/method. I have tested the current and power output, and they are float variables. Finally I used the line
int httpResponseCode = http.POST(httpRequestData);
to post the 3 data to the php file.
When I startup the Arduino, the output shows HTTP Response code: 200, which I believe the php file was successfully called (correct me if I am wrong). However, my database does not have any data inserted. Again the test.php prove that the database can be inserted with data.
Below is image of the database value inserted by the test.php file
Can anyone help me as I'm not sure what cause the Arduino to not able to post the data. Thanks!
you can't access your infinity free site with your arduino because infinity free have a security system
see https://support.infinityfree.net/websites/what-is-the-i-1-suffix/ for more info

Sending Arduino data to mySQL database using NodeMCU ESP8266

Kindly help me in my code. I have arduino code that is sending and getting data from mySql. It is running well and storing data to the database. The problem is that, if I switch ON the button the value 1 is stored in the database, but when I switch OFF the button the value 0 is not stored in the database.
Here is my arduino code:
//Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
s.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
bulbOnOff(buttonBulb);
}
int bulbOnOff(int buttonBulb) {
unsigned long currentMillis = millis();
// protect against overflow
if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
//Serial.println(!buttonBulb);
currentStatus = buttonBulb;
// update database here
if(s.available()>0)
{
s.write(!buttonBulb);
}
lastMillis = currentMillis;
}
}
return 0;
}
The following is nodeMCU ESP8266 code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone"; // Your wifi Name
const char* password = "Qaser.shah.123"; // Your wifi Password
const char *host = "172.20.10.6"; //Your pc or server (database) IP, example : 192.168.0.0 , if you are a windows os user, open cmd, then type ipconfig then look at IPv4 Address.
void setup() {
// put your setup code here, to run once:
wifiConnection();
s.begin(115200);
}
int wifiConnection() {
pinMode(Led_OnBoard, OUTPUT); // Initialize the Led_OnBoard pin as an output
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
digitalWrite(Led_OnBoard, HIGH);
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected to Network/SSID");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
s.write("s");
if (s.available() > 0)
{
buttonBulb = s.read();
Serial.println(buttonBulb);
int result = updateDatabase(buttonBulb);
if(result != 0){
//error updating database
Serial.print("error updating database");
}
}
}
int updateDatabase(int buttonBulb){
HTTPClient http; //Declare object of class HTTPClient
//String ButtonState;
String buttonValueSend, postData;
buttonValueSend = String(buttonBulb); //String to interger conversion
//Post Data
postData = "buttonBulb=" + buttonValueSend;
http.begin("http://172.20.10.6/Nodemcu_db_record_view/InsertDB.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
http.end(); //Close connection
return 0;
}
The following is my php code which stores the Arduino data
<?php
//Creates new record as per request
//Connect to database
$servername = "localhost"; //example = localhost or 192.168.0.0
$username = "root"; //example = root
$password = "";
$dbname = "automation";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
//Get current date and time
date_default_timezone_set('Asia/Karachi');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_POST['buttonBulb']))
{
$buttonBulb = $_POST['buttonBulb'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
See the image of output
In this image OK is printing at Value 1 but not printing OK at value 0
I think there is something wrong or I forgot something, that is why it is not happening.
Thanks a lot for any appericiation.
You can create a separate function to update the database and only call the update when the button state is changed.
Combined with my answer on your previous question it would look like this:
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database
int result = updateDatabase(buttonBulb);
if (result != 0) {
// error updating database
}
}
lastMillis = currentMillis;
}
}
int updateDatabase(int buttonvalue) {
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
buttonValueSend = String(buttonvalue); //String to integer conversion
// ...
http.end(); //Close connection
return 0; // for example return 0 on success, -1 on error
}
I have found the problem. The problem was in my php code that is why the 1 will stored in the database but 0 would not.
Here is what I have change in php code
I just removed if(!empty(&_POST['buttonBulb'])){}
The code that was used in if statement now it is outside from if statement.
Reason
The behind that, when I send 1 to this code it is OK but if send 0 the is statement assumes there is no value and buttonBulb variable is empty.
Thankyou all of you who help me in this code. Now I am going to next step of this project and if I have some problems I will ask.
Specially thanks to #Danny_ds

Can't Save URL Parameters in HTTP Get Request 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.

Angular $http post not working with a https url

In my ionic app I have the following code:
$http({ url: "http://someurl/script.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({param1:$localStorage.test.paramtest})
}).success(function(data) {
//console.log(data);
$scope.data = data;
}).error(function(data) {
//console.log("error:" + data);
alert("error:" + data);
})
.finally(function (data) {
//console.log("ok:" + data);
alert("ok:" + data);
});
The code above is working fine and I'm able to post en retrieve data from my database.
When I change the http:// url to a https:// url all of a sudden it is not working anymore. The error function gives me the error "error: null"
When I manually define the id in the php script and run de script with the https url in my browser it is also working.
This is mij script.php code:
<?php
//variables
$id = $_POST["param1"];
//$id = "12047";
// databse connection variables
$hostname = "...";
$username = "...";
$password = "...";
$database = "...";
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully<br>";
// show all database entries
$sql = "SELECT * FROM table1 WHERE field1_id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
// Add all rows to an array
$rows[] = $row;
}
// Json encode the full array
echo json_encode($rows);
} else {
//echo "0results";
}
$conn->close();
?>
I have setup my hosting to work with https and installed a SSL certificate on my server.
I found out that my hosting provider doesn't support SSL database connections in there hosting packages. It appears that this is only possible with dedicated servers.

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);

Categories