ESP32 can't POST data to PHP [HTTP Response code: 400]

Hello everyone
I am a beginner with ESP32 and I am developing a example where I show simple data to a web page hosted in CPanel, within CPanel I made two .php pages, one where the POST method will be executed and another where the data will be displayed .
The problem is when I upload the code, since when observing the serial monitor the following message appears:

The connection if it succeeds in establishing itself with the WIFI network but when it comes to wanting to send data, it does not send it.

My code is the following::

#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>

// Replace with your network credentials
const char* ssid     = "xxxxx";
const char* password = "xxxxx";

// Domain name and URL path or IP address with path
const char* serverName = "https://xxxx.xxx/post-esp32-data.php";

String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "LDR";
String sensorLocation = "Office";
int sensorValue;

void setup() {
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);
  //WiFi.setSleep (false); 
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;
    
    //Domain name with URL path or IP address with path
    http.begin(client, serverName);
    
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    sensorValue = analogRead(4);
    
    // Prepare HTTP POST request data
//sensor, location, value1, value2, value3 are rows of the table that i generated in PhpMyAdmin to show detail of sensor (this code line is for testing purposes without the LDR sensor)
    String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=LDR&location=Office&value1=24.75&value2=49.54&value3=1005.14";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);
    
    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
        
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);  
}

I tried change some values without lucky :frowning:
Thanks

I guess that your code is copied from here, and this applies only to HTTP requests. You cannot change this to encrypted HTTPS with an unencrypted client, so you might want to find some info about "WiFiClientSecure".

1 Like

Thanks bro! :sweat_smile: