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 = "tPmAT5Ab3j7F9";
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=tPmAT5Ab3j7F9&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 = "tPmAT5Ab3j7F9";

$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 . "
" . $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!

I'd probably proceed like this:

  1. print httpRequestData to see if it looks reasonable.
  2. change the sketch and the PHP to use the GET method instead of POST.
  3. Enter the full URL in a web browser which is connected to the same WLAN to attempt to isolate the problem. This should create a record in the database.
  4. Check the Apache log files.

your nginx server requires Javascript to be enabled in the connected client (and also a user agent). Your ESP does not qualify... (it is likely seen as a bot and access is refused)

can you switch to Apache? do you have control over the HTTP server?

On Arduino, you can print out the response from HTTP Server.
I would like to recommend making HTTP request without using library. This help you controls what you sent to HTTP Server.

You can follow to this Arduino MySQL via HTTP and Arduino makes HTTP request tutorial

I’ve just noticed @J-M-L’s comments and that your PHP code has embedded instructions referring to ESP32 handling. Post a link to the set up / configuration information you have been given for this service you have subscribed to ( smart switch - nginx or whatever ?) or the tutorial you are following.

There is an easy way to test:

You save this into test.htm

<html><body>
<form action="http://smartswitchfyp.rf.gd/post-data.php/api_key=tPmAT5Ab3j7F9" method="post">
value1: <input type="text" name="value1">
value2: <input type="text" name="value2">
<input type="submit">
</form></body></html>

replacing tPmAT5Ab3j7F9 by whatever is the real api_key

You submit, you check if that works and the data is in the database.

if that's OK then your post-data.php can be considered robust enough

The POST request looks like

http://smartswitchfyp.rf.gd/post-data.php/api_key=[color=blue]tPmAT5Ab3j7F9[/color]&value1=100&value2=200

Then to mimic what you've done in your ESP, you open up a unix terminal and type:

curl -X POST  -v "http://smartswitchfyp.rf.gd/post-data.php/api_key=tPmAT5Ab3j7F9&value1=100&value2=200"

if you do this you get an answer from your HTTP server that says "HTTP/1.1 403 Forbidden" --> that's because you did not provide a user agent

so if you give a user agent (as ESP32 - might want also to check with a full fledged one)

curl -X POST  -vA "ESP32" "http://smartswitchfyp.rf.gd/post-data.php/api_key=[color=blue]tPmAT5Ab3j7F9[/color]&value1=100&value2=200"

(in both cases use of course the right API key)

Then you get an answer from your nginx HTTP server that says "HTTP/1.1 200 OK" but you'll notice in the answer it also says

This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support

That's why it looks like to me your hosting provider has blocked requests that do not come from "legit" browsers with possibly cookies and javascript enabled.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.