Hey fellow Arduino enthusiasts,
I'm excited to be a part of this community! I've recently started working on a project involving an ESP8266 board and ran into a bit of a roadblock. I managed to find a code that successfully sends data to a web server hosted on 000webhost.com. However, I'm now trying to figure out how to receive data from the same web server back to my ESP8266.
Here's the code I'm using to send data to the server:
ESP Code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "testing";
const char* password = "testing123*";
const char* serverUrl = "http://esp8266.000webhostapp.com/submit.php"; // Change to your server URL
const char* uniqueID = "ESPdlf%**"; // Unique ID for the device
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
if (Serial.available()) {
String data = Serial.readStringUntil('\n'); // Read data from Serial monitor
String dataWithID = uniqueID + data; // Append the unique ID to the data
sendDataToServer(dataWithID);
}
}
void sendDataToServer(String data) {
WiFiClient client;
HTTPClient http;
http.begin(client, serverUrl);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String postData = "data=" + data + "&device_id=" + uniqueID; // Send unique ID with data
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("HTTP Response Code: " + String(httpResponseCode));
Serial.println("Server response: " + response);
} else {
Serial.println("HTTP POST request failed");
}
http.end();
}
PHP:
<?php
// Get the data and device ID from the POST request
$data = $_POST['data'];
$device_id = $_POST['device_id'];
// Sanitize and validate the input data
$data = htmlspecialchars($data); // Sanitize data to prevent HTML/JS injection
$device_id = htmlspecialchars($device_id); // Sanitize device ID
// Create HTML content to display the data and response
$response = "Data received";
$write = "<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> ESP Data </h1><br>
<div class='container'>
<p>Data: <span id='data'>$data</span></p>
<p>Device ID: <span id='device_id'>$device_id</span></p>
<p>Server Response: <span id='response'>$response</span></p>
</div>
</body>
</html>";
// Write the HTML content to the esp1.php file
file_put_contents('esp1.php', $write);
// Send a response to the client
echo $response;
?>
Now, I'd greatly appreciate your help in modifying this code or providing additional code snippets to enable the ESP8266 to receive data from the web server. Ideally, I'd like to receive the data in a format that I can then process and utilize within my project.
Thanks a lot in advance for your guidance and support! Looking forward to learning from this awesome community.