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

String apiKeyValue = "tPmAT5Ab3j7F9";

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

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

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: ");
    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
    else {
      Serial.print("Error code: ");
    // Free resources
  else {
    Serial.println("WiFi Disconnected");
  //Send an HTTP POST request every 30 seconds

I tried change some values without lucky :frowning:

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:

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