ESP8266: HTTP POST Requests

The objective of this post is to explain how to do POST requests from an ESP8266, using the Arduino IDE and the ESP8266 libraries.


Introduction

The objective of this post is to explain how to do POST requests from an ESP8266, using the Arduino IDE and the ESP8266 libraries. All the tests shown here were performed on a NodeMCU board, which you can find here at eBay for less than 5 euros.

If you prefer a video tutorial, please check the video bellow on my YouTube Channel.


The setup

First, we need to include some libraries, which should be available after the installation of the ESP8266 libraries for the Arduino IDE.

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

In the setup function, we will just initialize the Serial connection, in order to print the results of our application. Besides that, we need to establish a connection to an AP (Access Point), so the ESP8266 will be able to make the HTTP Requests. The code is specified bellow.

void setup() {

  Serial.begin(115200);                 //Serial connection
  WiFi.begin("yourSSID", "yourPASS");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

For more details on how to connect to a WiFi network, check this previous post.


The main code

In this section, we will analyze the code needed in the main loop function to perform the POST request. We will break the code and analyze the most relevant parts step by step, but the final code is summarized at the end of the section.

First of all, we need to declare an object of the class HTTPClient, from which we will call various methods to prepare the headers and content of the request, send it and check for the result. We will call this object simply “http”.

HTTPClient http;

After that, we call the begin method on the http object and pass the URL that we want to connect to and make the post request. In this case, I’m sending the post request to an application running on my local network, which is why I’m sending it the format seen bellow (Host IP:Port/Path).

http.begin("http://192.168.1.88:9999/hello");

Nevertheless, we can send the request to a website by specifying it’s domain name, as seen bellow (the destination website specified implements a dummy REST API for testing and prototyping).

http.begin("http://jsonplaceholder.typicode.com/users");

Next, we can define headers with the addHeader method. In this case, we are specifying the content-type as “text/plain”, since we will just send a simple string in the body.

http.addHeader("Content-Type", "text/plain");

The body of the request is specified as a parameter when calling the POST method on the HTTPClient object. In this case, we will simply send a string saying “Message from ESP8266”. The return value of this method corresponds to the HTTP response code and thus is important to check for error handling.

int httpCode = http.POST("Message from ESP8266");

We can now get the payload by calling the getString method, which will return the response payload as a string.

String payload = http.getString();

In the end, we need to call the end() method on the object to guarantee that the TCP connection is closed. This is very important to free the resources.

http.end();

Just to handle any possible WiFi connection errors, we will include a validation of the connection status before making the request. For debugging purposes, we will print both the response payload and the HTTP code.

The final code is specified bellow. To keep the code simpler and focus on the main subject, we did not check if the httpCode is less than zero, which indicates an error in the connection. Nevertheless, we should do so in the final code of an application.

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("yourSSID", "yourPASS");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://192.168.1.88:8085/hello");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("Message from ESP8266");   //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

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");   

 }

  delay(30000);  //Send a request every 30 seconds

}

 

Testing the code

In the context of this tutorial, I was sending the post requests to a mule application running in a machine on my local network. Just to illustrate the result, figure 1 shows the output of incoming requests on the console of the development environment. As can be seen in the bottom right, it is printing the “Message from ESP8266” string we defined early.

Mulesoft receiving post from ESP8266

Figure 1 – Output of the mule application that is receiving the POST requests.

Figure 2 shows the HTTP codes and response payloads for the POST requests. In this case, I defined a simple “Message received” string as response to the requests.

ESP8266 HTTP Post response

Figure 2 – Output of the POST requests.


Final Notes

As an alternative, the begin method used before can be called with other sets of parameters, as can be seen in the specification of the HTTPClient class. For example, we can pass the host IP, port and path as 3 different parameters, instead of a single string, amongst many other options.

The HTTPClient class also has a method to simplify debugging of a response to the request. So, if we want to print the response payload to the serial port, we can just call the writeToStream method and pass as argument a pointer to the Serial port, that we initialized before in the setup function. So, the call bellow is an alternative to the getString method used in the example:

http.writeToStream(&Serial);

These are just 2 alternative implementation examples. The HTTPClient class many other useful methods not used in this tutorial. You can check them here.


Technical details

ESP8266 libraries: v2.3.0.

117 Replies to “ESP8266: HTTP POST Requests”

  1. You’re welcome 🙂

    To be honest it will be hard to help without a prior knowledge on coding.

    The Arduino environment is very easy to get started, but it is important that you try t get some basic programming knowledge before going to a system like you mentioned, which is already considerably complex.

    My recommendation is that you try to learn the basics of the Arduino language before tackling more advanced topics such as using the ESP8266 WiFi. There are plenty of resources around the web about it.

    Although it is easy to find working code for the ESP8266 that we upload and works, it will be difficult to tweak it to suit your needs without some basic programming experience.

    Best regards,
    Nuno Santos

  2. You’re welcome 🙂
    To be honest it will be hard to help without a prior knowledge on coding.
    The Arduino environment is very easy to get started, but it is important that you try t get some basic programming knowledge before going to a system like you mentioned, which is already considerably complex.
    My recommendation is that you try to learn the basics of the Arduino language before tackling more advanced topics such as using the ESP8266 WiFi. There are plenty of resources around the web about it.
    Although it is easy to find working code for the ESP8266 that we upload and works, it will be difficult to tweak it to suit your needs without some basic programming experience.
    Best regards,
    Nuno Santos

  3. hello i am sending rfid ids to internet page with php. I just sometimes get some mistakes and I do not know how to solve it.
      for example if my internet connection slows down or disconnects, is the nodemcu reconnected? how can I connect again if not connected …
    sometimes dont reading the card ..

    https://github.com/fatihmehmetyy/nodemcurfid

    1. Hi! I’ve not been working for a while with the ESP8266 WiFi, but from the source files of the WiFi library I think it should automatically reconnect, or at least there’s a function that seems to allow that:

      https://github.com/esp8266/Arduino/blob/9dcc580aef055bd1c5226655abd5266c6049a54f/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.h

      My recommendation is that you try to test it separately from your RFID program. Basically, just set a simple program that connects to wifi, makes HTTP requests periodically to some website and prints them to the serial port.

      When setting the WiFi, just call the following function, by passing the value true as input (the function is the one I mentioned from the source files):
      bool setAutoReconnect(bool autoReconnect);

      Then disconnect the router for a while and connect it again and check if the ESP reconnects and starts making the requests again.

      I’m not sure it will work, but it seems that it should by the API.

      Not that the problem you are facing may not be caused by the WiFi but rather by some problem with your server.

      If you emulate some requests to your php webpage with another program (for example, writing a simple Python script to send HTTP test requests to it) how does it behave? Do you also get mistakes?

      I’ve seen a fair share of people having problems with the whole system and think that it was caused by the ESP and in fact it was the server that had some bugs.

      You may also have some problems with the RFID code. If are experiencing mistakes and not the absence of data, it may not be caused by the WiFi.

      When designing systems that have many parts communicating, the best approach is to test every part independently first before connecting the whole system. You should only start connecting everything when you are confident that each individual part is working as expected. Otherwise it will be a debugging nightmare.

      Hope this helps.
      Best regards,
      Nuno Santos

  4. hello i am sending rfid ids to internet page with php. I just sometimes get some mistakes and I do not know how to solve it.
      for example if my internet connection slows down or disconnects, is the nodemcu reconnected? how can I connect again if not connected …
    sometimes dont reading the card ..
    https://github.com/fatihmehmetyy/nodemcurfid

    1. Hi! I’ve not been working for a while with the ESP8266 WiFi, but from the source files of the WiFi library I think it should automatically reconnect, or at least there’s a function that seems to allow that:
      https://github.com/esp8266/Arduino/blob/9dcc580aef055bd1c5226655abd5266c6049a54f/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.h
      My recommendation is that you try to test it separately from your RFID program. Basically, just set a simple program that connects to wifi, makes HTTP requests periodically to some website and prints them to the serial port.
      When setting the WiFi, just call the following function, by passing the value true as input (the function is the one I mentioned from the source files):
      bool setAutoReconnect(bool autoReconnect);
      Then disconnect the router for a while and connect it again and check if the ESP reconnects and starts making the requests again.
      I’m not sure it will work, but it seems that it should by the API.
      Not that the problem you are facing may not be caused by the WiFi but rather by some problem with your server.
      If you emulate some requests to your php webpage with another program (for example, writing a simple Python script to send HTTP test requests to it) how does it behave? Do you also get mistakes?
      I’ve seen a fair share of people having problems with the whole system and think that it was caused by the ESP and in fact it was the server that had some bugs.
      You may also have some problems with the RFID code. If are experiencing mistakes and not the absence of data, it may not be caused by the WiFi.
      When designing systems that have many parts communicating, the best approach is to test every part independently first before connecting the whole system. You should only start connecting everything when you are confident that each individual part is working as expected. Otherwise it will be a debugging nightmare.
      Hope this helps.
      Best regards,
      Nuno Santos

  5. my “httpCode” returns -1 .. means it isn’t sending data to website..here is a code if i made something wrong to the code please guide me. Thanks!..
    #include
    #include
    void setup() {
    Serial.begin(115200); //Serial connection
    WiFi.begin(“ZONG MBB-E5573-C840”, “77423072”); //WiFi connection
    Serial.println(“Setup iniated”);
    while (WiFi.status() != 3) { //Wait for the WiFI connection completion
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WIFI STATUS : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }

    void loop() {
    HTTPClient http;
    //String Data = “x=” + (String)distance + “&y=” + (String)MAX_HEIGHT + “&z=0”;
    String Data = “x=Jungli&y=Billi&z=Wild”;
    http.begin(“https://testingblahblah.000webhostapp.com/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    int sent = http.POST(“x=Jungli&y=Billi&z=Wild”);
    Serial.println(sent);
    String httpPayload = http.getString();
    Serial.println(httpPayload);
    if(sent > 0)
    {
    Serial.println(“Message has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    delay(20000);
    }

    1. Hi! You are trying to reach an HTTPS (not the S from secure after HTTP).

      This code is not suitable for using with HTTPS websites. When you contact a HTTPS website, you need to deal with stuff such as digital certificates and encryption.

      In the past, there was some support for that on the ESP8266, but it was pretty limited and didn’t allow to validate a whole certificate chain, we could simply hardcode the sha fingerprint of the certificate of the client we were trying to contact, which was not that much useful in terms of security.

      I’ve not been using the ESP8266 for a while, so I’m not sure if things have evolved since then. But at least, they still have the original HTTPS example:
      https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino

      If you really need HTTPS, my recommendation is that you take a look at the ESP32, the “evolution” of the ESP8266. It handles HTTPS very well and is able to validate the whole certificate chain.

      Hope it helps.

      Best regards,
      Nuno Santos

  6. my “httpCode” returns -1 .. means it isn’t sending data to website..here is a code if i made something wrong to the code please guide me. Thanks!..
    #include
    #include
    void setup() {
    Serial.begin(115200); //Serial connection
    WiFi.begin(“ZONG MBB-E5573-C840”, “77423072”); //WiFi connection
    Serial.println(“Setup iniated”);
    while (WiFi.status() != 3) { //Wait for the WiFI connection completion
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WIFI STATUS : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }
    void loop() {
    HTTPClient http;
    //String Data = “x=” + (String)distance + “&y=” + (String)MAX_HEIGHT + “&z=0”;
    String Data = “x=Jungli&y=Billi&z=Wild”;
    http.begin(“https://testingblahblah.000webhostapp.com/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    int sent = http.POST(“x=Jungli&y=Billi&z=Wild”);
    Serial.println(sent);
    String httpPayload = http.getString();
    Serial.println(httpPayload);
    if(sent > 0)
    {
    Serial.println(“Message has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    delay(20000);
    }

    1. Hi! You are trying to reach an HTTPS (not the S from secure after HTTP).
      This code is not suitable for using with HTTPS websites. When you contact a HTTPS website, you need to deal with stuff such as digital certificates and encryption.
      In the past, there was some support for that on the ESP8266, but it was pretty limited and didn’t allow to validate a whole certificate chain, we could simply hardcode the sha fingerprint of the certificate of the client we were trying to contact, which was not that much useful in terms of security.
      I’ve not been using the ESP8266 for a while, so I’m not sure if things have evolved since then. But at least, they still have the original HTTPS example:
      https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino
      If you really need HTTPS, my recommendation is that you take a look at the ESP32, the “evolution” of the ESP8266. It handles HTTPS very well and is able to validate the whole certificate chain.
      Hope it helps.
      Best regards,
      Nuno Santos

    1. Hi sir! One more thing i want to ask you is that i am actually working on a project to send ultrasonic sensor values to website, for that i tested your code for passing raw data to website and it works fine.. now i am confused how to make some changes to tested code regarding ultrasonic sensor.. i am posting my ultrasonic code here.that you could help me out to re-write this code according to sensor. I will be very thankful..

      int trigger=13;
      int echo=12;

      void setup()
      {

      Serial.begin(9600);
      pinMode(trigger,OUTPUT);
      pinMode(echo,INPUT);
      }

      void loop()
      {
      float time=0,distance=0;
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      digitalWrite(trigger,HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      time=pulseIn(echo,HIGH);
      distance=time*340/20000;

      Serial.print(“Distance:\n”);
      Serial.print(distance);
      Serial.print(“cm\n”);
      Serial.print(“Distance:\n”);
      Serial.print(distance/100);
      Serial.print(“m\n”);
      delay(1000);
      }

      1. Adapting the code should be simple. In the original example you shared, instead of using the x and y variables in the POST method, you can build a string of data with your distance variable from this code.

        Just as a note, if you want you can send the content of the POST request as JSON, since the ESP8266 can handle JSON very well.

        A good library is the ArduinoJson.

        Best regards,
        Nuno Santos

    2. Hi! I’m glad it is working for you 🙂 Just take in consideration that once you remove the S from the HTTPS you are now longer sending the content encrypted.

      Thus, all the things you are sending to your website are in plain text and can be easily intercepted by an attacker. Please take this in consideration if you are sending sensitive data.

    1. Hi sir! One more thing i want to ask you is that i am actually working on a project to send ultrasonic sensor values to website, for that i tested your code for passing raw data to website and it works fine.. now i am confused how to make some changes to tested code regarding ultrasonic sensor.. i am posting my ultrasonic code here.that you could help me out to re-write this code according to sensor. I will be very thankful..
      int trigger=13;
      int echo=12;
      void setup()
      {
      Serial.begin(9600);
      pinMode(trigger,OUTPUT);
      pinMode(echo,INPUT);
      }
      void loop()
      {
      float time=0,distance=0;
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      digitalWrite(trigger,HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      time=pulseIn(echo,HIGH);
      distance=time*340/20000;
      Serial.print(“Distance:\n”);
      Serial.print(distance);
      Serial.print(“cm\n”);
      Serial.print(“Distance:\n”);
      Serial.print(distance/100);
      Serial.print(“m\n”);
      delay(1000);
      }

      1. Adapting the code should be simple. In the original example you shared, instead of using the x and y variables in the POST method, you can build a string of data with your distance variable from this code.
        Just as a note, if you want you can send the content of the POST request as JSON, since the ESP8266 can handle JSON very well.
        A good library is the ArduinoJson.
        Best regards,
        Nuno Santos

    2. Hi! I’m glad it is working for you 🙂 Just take in consideration that once you remove the S from the HTTPS you are now longer sending the content encrypted.
      Thus, all the things you are sending to your website are in plain text and can be easily intercepted by an attacker. Please take this in consideration if you are sending sensitive data.

  7. Hell sir! i am having trouble to send ultrasonic sensor values to my webserver, seems like ultrasonic is not taking reading , and it sends o value to server , is there a problem of insufficient current for ultrasonic sensor or there is another problem plz help here is a Code. if any mistake found plz let me know.
    .NOTE: i check the simple code for ultrasonic and it works perfect.

    #include
    #include
    #define trigger 12
    # define echo 13
    float timex = 0;
    float distance = 0;
    float max_height = 0;
    float extra_space = 4.00;

    int TANK_SPECIAL_ID = 1;

    void setup() {

    pinMode(trigger,OUTPUT);
    pinMode(echo,INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin(“AndroidAP”, “lovely12”);

    Serial.println(“Setup Initiated\n”);

    while (WiFi.status() !=3) {
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WiFi Status : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }

    void loop() {
    HTTPClient http;
    int Percentage = 0;
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    digitalWrite(trigger,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    timex = pulseIn(echo,HIGH);
    distance = timex * 340 / 20000;

    if (max_height == 0) {
    Serial.println(“Setting max_height”);
    max_height = distance;
    Serial.println(“max_height configured.. 5 seconds delay”);
    delay(5000);
    Percentage = -1;
    Serial.print(“MAX HEIGHT: “);
    Serial.println(max_height);
    } else {
    int revVal = int(distance / max_height * 100);
    Percentage = revVal – 100;
    Serial.print(“Current Ratings: “);
    Serial.print(distance);
    Serial.print(” cm”);
    Serial.print(” | Percentage: “);
    Serial.print(Percentage);
    Serial.println(” %”);

    }
    if(distance > -1) {

    String Data = “x=” + String(Percentage) + “&y=” + String(max_height) + “&z=” + String(TANK_SPECIAL_ID);
    http.begin(“http://zaptraff.atwebpages.com/IOT/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

    int sent = http.POST(Data);
    Serial.print(“Request val:”);
    Serial.println(sent);
    //String httpPayload = http.getString();
    //Serial.println(httpPayload);
    if(sent > 0) {
    Serial.println(“Data has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    }

    delay(1000);
    }

    1. Hi!

      You will need to divide your debugging in steps. In this code, are you able to get the values from the sensor and print them, before trying to send them from the server?

      1. yeah! i separated the code of ultrasonic sensor when i change the board from Generic ESP8266 to arduino UNO than it gives the values to serial monitor but when i switch the board to generic and try to run whole code than it’s not working.. i also tried to give external 5v power for ultrasonic sensor but nothing works. i don’t get what’s the real problem.

  8. Hell sir! i am having trouble to send ultrasonic sensor values to my webserver, seems like ultrasonic is not taking reading , and it sends o value to server , is there a problem of insufficient current for ultrasonic sensor or there is another problem plz help here is a Code. if any mistake found plz let me know.
    .NOTE: i check the simple code for ultrasonic and it works perfect.
    #include
    #include
    #define trigger 12
    # define echo 13
    float timex = 0;
    float distance = 0;
    float max_height = 0;
    float extra_space = 4.00;
    int TANK_SPECIAL_ID = 1;
    void setup() {
    pinMode(trigger,OUTPUT);
    pinMode(echo,INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin(“AndroidAP”, “lovely12”);
    Serial.println(“Setup Initiated\n”);
    while (WiFi.status() !=3) {
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WiFi Status : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }
    void loop() {
    HTTPClient http;
    int Percentage = 0;
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    digitalWrite(trigger,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    timex = pulseIn(echo,HIGH);
    distance = timex * 340 / 20000;
    if (max_height == 0) {
    Serial.println(“Setting max_height”);
    max_height = distance;
    Serial.println(“max_height configured.. 5 seconds delay”);
    delay(5000);
    Percentage = -1;
    Serial.print(“MAX HEIGHT: “);
    Serial.println(max_height);
    } else {
    int revVal = int(distance / max_height * 100);
    Percentage = revVal – 100;
    Serial.print(“Current Ratings: “);
    Serial.print(distance);
    Serial.print(” cm”);
    Serial.print(” | Percentage: “);
    Serial.print(Percentage);
    Serial.println(” %”);
    }
    if(distance > -1) {
    String Data = “x=” + String(Percentage) + “&y=” + String(max_height) + “&z=” + String(TANK_SPECIAL_ID);
    http.begin(“http://zaptraff.atwebpages.com/IOT/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    int sent = http.POST(Data);
    Serial.print(“Request val:”);
    Serial.println(sent);
    //String httpPayload = http.getString();
    //Serial.println(httpPayload);
    if(sent > 0) {
    Serial.println(“Data has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    }
    delay(1000);
    }

    1. Hi!
      You will need to divide your debugging in steps. In this code, are you able to get the values from the sensor and print them, before trying to send them from the server?

      1. yeah! i separated the code of ultrasonic sensor when i change the board from Generic ESP8266 to arduino UNO than it gives the values to serial monitor but when i switch the board to generic and try to run whole code than it’s not working.. i also tried to give external 5v power for ultrasonic sensor but nothing works. i don’t get what’s the real problem.

  9. Hi,
    I’m trying to send a String which is my name to a php file in the localhost then using POST method then simply print it to the browser here is my Arduino sketsh and PHP file:

    #include
    #include

    char ssid[]= “AT-4GLTE-E5172AS-22-FC8C8”;
    char pass[]= “J1BY051TB4E”;
    String url=”http://192.168.1.2/NodeMcu_tests/hellow.php”;
    String name=”Dimaria”;

    void setup() {
    Serial.begin(9600);
    delay(500);
    connect_to_wifi();

    if(WiFi.status() ==WL_CONNECTED)
    {
    HTTPClient http;
    http.begin(url);
    http.addHeader(“Content-Type”,”text/plain”);
    http.POST(“name=”+name);
    http.end();

    }

    else

    Serial.println(“Erreur WiFi !!!!!!!!”);

    }

    void loop() {

    }

    void connect_to_wifi()
    {

    Serial.print(“Connecting ………..”);
    delay(500);
    WiFi.disconnect();
    WiFi.begin(ssid,pass);

    while(WiFi.status() !=WL_CONNECTED)
    {
    delay(500);
    Serial.println(“…..”);

    }
    Serial.println(“Successfully connected”);

    }

    php file:

    but unfortunatly I have got not thing printed but Undifined reference to name.

    thanks for your attention……

    1. Hi!

      Sorry wordpress probably doesn’t allow you to post php source code in comments :/

      Nonetheless, I’m assuming the “undefined reference to name” you mention is on the PHP side right?

      Unfortunately I don’t know much about PHP so I cannot help you with that part of the code.

      Nonetheless, my recommendation is that you test things separately before going for the end to end.

      Have you tried to send the request to the PHP page from a tool such as Postman to confirm that your backend is working correctly?

      If it still gives you that problem, then the problem is on your backend you need to focus on debugging the backend code.

      Just a note, you shouldn’t share the credentials of your wifi network in comments on the web, due to security reasons 🙂

      Best regards,
      Nuno Santos

      1. Thanks bro for your advice and which concern wifi credentials it’s a Evil Twin Ap don’t worry about it I do know what to do 😉

  10. Hi,
    I’m trying to send a String which is my name to a php file in the localhost then using POST method then simply print it to the browser here is my Arduino sketsh and PHP file:
    #include
    #include
    char ssid[]= “AT-4GLTE-E5172AS-22-FC8C8”;
    char pass[]= “J1BY051TB4E”;
    String url=”http://192.168.1.2/NodeMcu_tests/hellow.php”;
    String name=”Dimaria”;
    void setup() {
    Serial.begin(9600);
    delay(500);
    connect_to_wifi();
    if(WiFi.status() ==WL_CONNECTED)
    {
    HTTPClient http;
    http.begin(url);
    http.addHeader(“Content-Type”,”text/plain”);
    http.POST(“name=”+name);
    http.end();
    }
    else
    Serial.println(“Erreur WiFi !!!!!!!!”);
    }
    void loop() {
    }
    void connect_to_wifi()
    {
    Serial.print(“Connecting ………..”);
    delay(500);
    WiFi.disconnect();
    WiFi.begin(ssid,pass);
    while(WiFi.status() !=WL_CONNECTED)
    {
    delay(500);
    Serial.println(“…..”);
    }
    Serial.println(“Successfully connected”);
    }
    php file:
    but unfortunatly I have got not thing printed but Undifined reference to name.
    thanks for your attention……

    1. Hi!
      Sorry wordpress probably doesn’t allow you to post php source code in comments :/
      Nonetheless, I’m assuming the “undefined reference to name” you mention is on the PHP side right?
      Unfortunately I don’t know much about PHP so I cannot help you with that part of the code.
      Nonetheless, my recommendation is that you test things separately before going for the end to end.
      Have you tried to send the request to the PHP page from a tool such as Postman to confirm that your backend is working correctly?
      If it still gives you that problem, then the problem is on your backend you need to focus on debugging the backend code.
      Just a note, you shouldn’t share the credentials of your wifi network in comments on the web, due to security reasons 🙂
      Best regards,
      Nuno Santos

      1. Thanks bro for your advice and which concern wifi credentials it’s a Evil Twin Ap don’t worry about it I do know what to do 😉

  11. i’ been facing problem since last week that i can’t get ultrasonic readings
    when i connect with my esp8266 wifi module ,everytime it gives 0cm reading.My

    both hardwares work perfectly if i connect them individually. is there any logical problem please help Sir 🙁

          1. Thanks! but i have been facing new problem as my recent solution was to connect Gpio pin for data trasnmission that act as bridge between arduino board and esp8266. so simply i connect esp8266 GPIO2 pin with ultrasonic sensor echo pin and that echo pin was connected by arduino board digital pin 2 and i directly connected the trig pin. it was working fine. but sometime i get stuck with constant 0 reading and sometime constant 100 reading i can’t find what the actual problem is.. am i doing right by connecting only one echo pin with esp8266 Gpio pin or do i need to connect both echo and trig pin to other Gpio pin
            Note: i have only two GPIO pin in esp8266- esp-01 one is GPIO0 for flashing and uplaoding data and another one is for trasnmitting data GPIO2 . plesae help what should i do . code are the same as above didn’t change anything thanks

            1. Hi! Sorry, unfortunately I’ve never worked with the ultrassonic sensor on the ESP, I can’t give you much assistance :/

              But check if yo have all the gnds connected, it may be the source of your problem.

              If it is possible for your project, you can also move everything to an ESP board that exposes all the pins of the ESP8266. The ESP-01 is very limiting in that aspect, but there are plenty of ESP8266 boards out there with lots of pins you can use, without the need for the arduino board.

  12. i’ been facing problem since last week that i can’t get ultrasonic readings
    when i connect with my esp8266 wifi module ,everytime it gives 0cm reading.My
    both hardwares work perfectly if i connect them individually. is there any logical problem please help Sir 🙁

          1. Thanks! but i have been facing new problem as my recent solution was to connect Gpio pin for data trasnmission that act as bridge between arduino board and esp8266. so simply i connect esp8266 GPIO2 pin with ultrasonic sensor echo pin and that echo pin was connected by arduino board digital pin 2 and i directly connected the trig pin. it was working fine. but sometime i get stuck with constant 0 reading and sometime constant 100 reading i can’t find what the actual problem is.. am i doing right by connecting only one echo pin with esp8266 Gpio pin or do i need to connect both echo and trig pin to other Gpio pin
            Note: i have only two GPIO pin in esp8266- esp-01 one is GPIO0 for flashing and uplaoding data and another one is for trasnmitting data GPIO2 . plesae help what should i do . code are the same as above didn’t change anything thanks

            1. Hi! Sorry, unfortunately I’ve never worked with the ultrassonic sensor on the ESP, I can’t give you much assistance :/
              But check if yo have all the gnds connected, it may be the source of your problem.
              If it is possible for your project, you can also move everything to an ESP board that exposes all the pins of the ESP8266. The ESP-01 is very limiting in that aspect, but there are plenty of ESP8266 boards out there with lots of pins you can use, without the need for the arduino board.

    1. Hi!

      Sorry I haven’t yet worked with XML in the ESP8266.

      I usually use JSON because it has much less overhead. Maybe you can find some XML libraries for the Arduino environment around the web.

      Best regards,
      Nuno Santos

    1. Hi!
      Sorry I haven’t yet worked with XML in the ESP8266.
      I usually use JSON because it has much less overhead. Maybe you can find some XML libraries for the Arduino environment around the web.
      Best regards,
      Nuno Santos

    1. Hi! Thanks for the feedback 🙂

      Well that’s a too generic topic that can be tackled in many ways. 🙂

      What do you mean by Own Domain Web page?

      Regarding the sensor, you need to read your measurements (most likely periodically) and send them as the body of your post request.

      You need to choose a suitable data format. I typically use JSON, is lightweight and you have plenty of parsers.

      Hope it helps,
      Nuno Santos

        1. Hi!

          As long as your backend is able to receive HTTP Post requests, you should be able to use this code to send data to it, assuming that continuously is without a persistent connection and at a rate supported by the ESP and the backend.

          Best regards,
          Nuno Santos

    1. Hi! Thanks for the feedback 🙂
      Well that’s a too generic topic that can be tackled in many ways. 🙂
      What do you mean by Own Domain Web page?
      Regarding the sensor, you need to read your measurements (most likely periodically) and send them as the body of your post request.
      You need to choose a suitable data format. I typically use JSON, is lightweight and you have plenty of parsers.
      Hope it helps,
      Nuno Santos

        1. Hi!
          As long as your backend is able to receive HTTP Post requests, you should be able to use this code to send data to it, assuming that continuously is without a persistent connection and at a rate supported by the ESP and the backend.
          Best regards,
          Nuno Santos

  13. Hi antepher, fantastic post.

    I have a question:
    I was able to successfully do an HTTP POST request to httpbin.org.
    httpbin.org replies with code 200 and the following:
    Response from server is{
    “args”: {},
    “data”: “PHESS test sentence”,
    “files”: {},
    “form”: {},
    “headers”: {
    “Accept-Encoding”: “identity;q=1,chunked;q=0.1,*;q=0”,
    “Connection”: “close”,
    “Content-Length”: “19”,
    “Content-Type”: “text/plain”,
    “Host”: “httpbin.org”,
    “User-Agent”: “ESP8266HTTPClient”
    },
    “json”: null,
    “origin”: “71.94.131.30”,
    “url”: “http://httpbin.org/post”
    }

    How would I be able to retrieve that data on another network from another computer?

    Again, thanks a lot!

    1. Hi Daniel,

      Thank you very much for the feedback, I’m glad it is working for you 🙂

      What do you mean by retrieving that data from another network on another computer?

      Like having a local web server serving content for your ESP?

      Let me know a little bit more about what you are trying to do to see if I can help 🙂

      Best regards,
      Nuno Santos

  14. Hi antepher, fantastic post.
    I have a question:
    I was able to successfully do an HTTP POST request to httpbin.org.
    httpbin.org replies with code 200 and the following:
    Response from server is{
    “args”: {},
    “data”: “PHESS test sentence”,
    “files”: {},
    “form”: {},
    “headers”: {
    “Accept-Encoding”: “identity;q=1,chunked;q=0.1,*;q=0”,
    “Connection”: “close”,
    “Content-Length”: “19”,
    “Content-Type”: “text/plain”,
    “Host”: “httpbin.org”,
    “User-Agent”: “ESP8266HTTPClient”
    },
    “json”: null,
    “origin”: “71.94.131.30”,
    “url”: “http://httpbin.org/post”
    }
    How would I be able to retrieve that data on another network from another computer?
    Again, thanks a lot!

    1. Hi Daniel,
      Thank you very much for the feedback, I’m glad it is working for you 🙂
      What do you mean by retrieving that data from another network on another computer?
      Like having a local web server serving content for your ESP?
      Let me know a little bit more about what you are trying to do to see if I can help 🙂
      Best regards,
      Nuno Santos

  15. Hello Nuno,

    I am trying to POST sensor data from one Esp 8266 to another. Here is the code from the client(station).
    http.begin(“http://192.168.4.1:80/w”);
    I am getting wdg resets when POSTing to the server, On debugging it shows,
    [hostByName] Host: 192.168.4.1 is a IP!
    :ref 1

    Here is my client code snippet. Still can’t find out the problem,…

    // Static network configuration
    IPAddress ip(192, 168, 4, 4);
    IPAddress gateway(192, 168, 4, 1);
    IPAddress subnet(255, 255, 255, 0);

    WiFiClient client;

    void setup() {
    ESP.eraseConfig();
    WiFi.persistent(false);
    Serial.begin(115200);
    delay(500);
    pinMode(ESPLED, OUTPUT);
    WiFi.mode(WIFI_STA);
    ESP.wdtDisable();
    ESP.wdtEnable(WDTO_8S);
    WiFi.config(ip, gateway, subnet);
    WiFi.begin(ssid, password);
    Serial.println(“”);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    counter++;
    }
    }

    void sendHttpRequest(String Content)
    {
    HTTPClient http;
    http.begin(“http://192.168.4.1:80/w”);
    http.addHeader(“Content-Type”, “text/plain”);
    int k= http.POST(“Lvl = 2134123”);
    Serial.println(k);
    http.writeToStream(&Serial);
    http.end();
    }

    Here is my server code

    void handle_feed() {
    String t = server.arg(“Lvl”);
    Serial.print(t);
    server.send(200, “text/plain”, “Received Level”);
    }

    void handleRoot() {

    server.send(200, “text/plain”, “Resolved by dns”);
    }

    void setup() {
    pinMode(TRIGGER_PIN,OUTPUT);

    Serial.begin(115200);
    WiFi.mode(WIFI_AP);

    Serial.println(“** SETUP ACCESS POINT **”);
    Serial.println(“- disconnect from any other modes”);
    WiFi.disconnect();
    Serial.println(“- start ap with SID: “+ String(ssid));
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print(“- AP IP address is :”);
    Serial.print(myIP);
    Serial.println(“** SETUP SERVER **”);
    Serial.println(“- starting server :”);
    server.on(“/”, handleRoot);
    server.on(“/w”, handle_feed);
    server.begin();
    if(MDNS.begin(“myesp”))
    {
    Serial.println(“DNS Started”);
    }
    MDNS.addService(“http”, “tcp”, 80);
    }

    void loop() {

    server.handleClient();

    }

    1. Hi!

      That’s weird, never experienced that problem.

      Why are you changing the watchdog values? You are trying to increase the time before it fires right? Does it also not work if you remove those calls?

      How much time does it take to trigger the watchdog? Is it immediate, like it resets as soon as it makes the request, or does it take a while, like the program is hanging somewhere?

      If you test your server isolated, like making a request from a tool such as Postman, does it answer in reasonable time or does it hang?

      If it is hanging, then it may be your server not responding fast enough, leaving the client hanging and eventually triggering the watchdog.

      Also, if you try sending the same client request to a dummy website, like this:
      https://jsonplaceholder.typicode.com/
      does it also reset?

      For now, it seems to be the best option trying to check where the problem lies, since looking at the end to end system will be harder. So my suggestion is that you try to check if the problem is on the client or on the server.

      Another suggestion is to post an issue on the git hub pages of the ESP8266 Arduino libraries, so maybe someone has already also experienced something similar.

      Hope this helps you going in the right track 🙂

      Best regards,
      Nuno Santos

  16. Hello Nuno,
    I am trying to POST sensor data from one Esp 8266 to another. Here is the code from the client(station).
    http.begin(“http://192.168.4.1:80/w”);
    I am getting wdg resets when POSTing to the server, On debugging it shows,
    [hostByName] Host: 192.168.4.1 is a IP!
    :ref 1
    Here is my client code snippet. Still can’t find out the problem,…
    // Static network configuration
    IPAddress ip(192, 168, 4, 4);
    IPAddress gateway(192, 168, 4, 1);
    IPAddress subnet(255, 255, 255, 0);
    WiFiClient client;
    void setup() {
    ESP.eraseConfig();
    WiFi.persistent(false);
    Serial.begin(115200);
    delay(500);
    pinMode(ESPLED, OUTPUT);
    WiFi.mode(WIFI_STA);
    ESP.wdtDisable();
    ESP.wdtEnable(WDTO_8S);
    WiFi.config(ip, gateway, subnet);
    WiFi.begin(ssid, password);
    Serial.println(“”);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    counter++;
    }
    }
    void sendHttpRequest(String Content)
    {
    HTTPClient http;
    http.begin(“http://192.168.4.1:80/w”);
    http.addHeader(“Content-Type”, “text/plain”);
    int k= http.POST(“Lvl = 2134123”);
    Serial.println(k);
    http.writeToStream(&Serial);
    http.end();
    }
    Here is my server code
    void handle_feed() {
    String t = server.arg(“Lvl”);
    Serial.print(t);
    server.send(200, “text/plain”, “Received Level”);
    }
    void handleRoot() {
    server.send(200, “text/plain”, “Resolved by dns”);
    }
    void setup() {
    pinMode(TRIGGER_PIN,OUTPUT);
    Serial.begin(115200);
    WiFi.mode(WIFI_AP);
    Serial.println(“** SETUP ACCESS POINT **”);
    Serial.println(“- disconnect from any other modes”);
    WiFi.disconnect();
    Serial.println(“- start ap with SID: “+ String(ssid));
    WiFi.softAP(ssid, password);
    IPAddress myIP = WiFi.softAPIP();
    Serial.print(“- AP IP address is :”);
    Serial.print(myIP);
    Serial.println(“** SETUP SERVER **”);
    Serial.println(“- starting server :”);
    server.on(“/”, handleRoot);
    server.on(“/w”, handle_feed);
    server.begin();
    if(MDNS.begin(“myesp”))
    {
    Serial.println(“DNS Started”);
    }
    MDNS.addService(“http”, “tcp”, 80);
    }
    void loop() {
    server.handleClient();
    }

    1. Hi!
      That’s weird, never experienced that problem.
      Why are you changing the watchdog values? You are trying to increase the time before it fires right? Does it also not work if you remove those calls?
      How much time does it take to trigger the watchdog? Is it immediate, like it resets as soon as it makes the request, or does it take a while, like the program is hanging somewhere?
      If you test your server isolated, like making a request from a tool such as Postman, does it answer in reasonable time or does it hang?
      If it is hanging, then it may be your server not responding fast enough, leaving the client hanging and eventually triggering the watchdog.
      Also, if you try sending the same client request to a dummy website, like this:
      https://jsonplaceholder.typicode.com/
      does it also reset?
      For now, it seems to be the best option trying to check where the problem lies, since looking at the end to end system will be harder. So my suggestion is that you try to check if the problem is on the client or on the server.
      Another suggestion is to post an issue on the git hub pages of the ESP8266 Arduino libraries, so maybe someone has already also experienced something similar.
      Hope this helps you going in the right track 🙂
      Best regards,
      Nuno Santos

  17. Hi
    If I host a local server on my laptop. How can I request to it through nodemcu. Or more precisely what will be the IP address to my localhost server?

    1. Hi!

      It should be the local IP of your laptop in the network.

      Depending on the framework you are using you may have to explicitly bind the server to the local IP.

      If you are on windows, you should be able to get the IP with a ipconfig command, and on linux with a ifconfig command, on the command line.

      Note that the ESP8266 needs to be connected to the same network of your laptop.

      Hope it helps.

      Best regards,
      Nuno Santos

  18. Hi
    If I host a local server on my laptop. How can I request to it through nodemcu. Or more precisely what will be the IP address to my localhost server?

    1. Hi!
      It should be the local IP of your laptop in the network.
      Depending on the framework you are using you may have to explicitly bind the server to the local IP.
      If you are on windows, you should be able to get the IP with a ipconfig command, and on linux with a ifconfig command, on the command line.
      Note that the ESP8266 needs to be connected to the same network of your laptop.
      Hope it helps.
      Best regards,
      Nuno Santos

  19. Thanks for a great post. Can I use this to send data from nodemcu to the firebase cloud functions using json format. If so can you please reply with a small code for the same. Just the main part will be enough. Thanks for the help.

    1. Hi! Thanks for the feedback 🙂

      Unfortunately I never had the chance to test it against firebase :/ I don’t know how fire base works, but if it uses regular HTTP you should be able to.

      Here is a tutorial on how to work with json and the esp8266:
      https://techtutorialsx.com/2016/08/10/esp8266-encoding-json-messages/

      Note however if firebase only works with HTTPS, then you will not be able to reach it using the code shown here.

      At the time I’ve been using the ESP8266, it didn’t manage HTTPS very well, due to the need to validate the whole certificate chain.

      As alternative, if you really need HTTPS and still have plenty of resources to develop your application, my suggestion is to take a look at the ESP32:
      https://techtutorialsx.com/2017/11/18/esp32-arduino-https-get-request/

      Best regards,
      Nuno Santos

  20. Thanks for a great post. Can I use this to send data from nodemcu to the firebase cloud functions using json format. If so can you please reply with a small code for the same. Just the main part will be enough. Thanks for the help.

    1. Hi! Thanks for the feedback 🙂
      Unfortunately I never had the chance to test it against firebase :/ I don’t know how fire base works, but if it uses regular HTTP you should be able to.
      Here is a tutorial on how to work with json and the esp8266:
      https://techtutorialsx.com/2016/08/10/esp8266-encoding-json-messages/
      Note however if firebase only works with HTTPS, then you will not be able to reach it using the code shown here.
      At the time I’ve been using the ESP8266, it didn’t manage HTTPS very well, due to the need to validate the whole certificate chain.
      As alternative, if you really need HTTPS and still have plenty of resources to develop your application, my suggestion is to take a look at the ESP32:
      https://techtutorialsx.com/2017/11/18/esp32-arduino-https-get-request/
      Best regards,
      Nuno Santos

    1. Hi!

      Not sure if I understood your question.

      You can use this code to send a HTTP post request (with data) to a server.

      A HTTP web server may be implemented with a lot of technologies, doesn’t need to be php.

      Your host may not be a computer, for instance, your host can be another ESP8266 and you can use this code to send data to it.

      Nonetheless, you need some device to host your server / website.

      When you mean continuously, do you mean like periodic, or like “real time” with a persistent connection (real time here is an abuse of language since it has another meaning in the world of embedded systems, but is a term commonly used)?

      If you need a persistent connection, then it is better to switch to something like using a direct socket connection.

      Hope this helps 🙂

    1. Hi!
      Not sure if I understood your question.
      You can use this code to send a HTTP post request (with data) to a server.
      A HTTP web server may be implemented with a lot of technologies, doesn’t need to be php.
      Your host may not be a computer, for instance, your host can be another ESP8266 and you can use this code to send data to it.
      Nonetheless, you need some device to host your server / website.
      When you mean continuously, do you mean like periodic, or like “real time” with a persistent connection (real time here is an abuse of language since it has another meaning in the world of embedded systems, but is a term commonly used)?
      If you need a persistent connection, then it is better to switch to something like using a direct socket connection.
      Hope this helps 🙂

    1. Hi! Thank you very much for the feedback 🙂

      Yes you should be able to use both HTTP request methods on your program.

      When you mention at the same time, I’m assuming that it is in the same program, but one request after another, right?

      Best regards,
      Nuno Santos

    1. Hi! Thank you very much for the feedback 🙂
      Yes you should be able to use both HTTP request methods on your program.
      When you mention at the same time, I’m assuming that it is in the same program, but one request after another, right?
      Best regards,
      Nuno Santos

  21. Hey Antepher,
    thanks for sharing with us this project!
    Im having a problem with a simple project i am trying to do, I hope you can help me-

    my MySQL DB(Cpanel server) include a table “Alerts” that have- day,hour(4 different hours 9,14,19,22),cell,status(if the button pressed). we try to light a led when the time “now” equals to the alert schedule.
    in the sending data -what i thought is that after the button is being pressed it will send 0/1 to the server to change the “status”.
    in the receiving data- i need to get the cell the day and the hour to light the button.

    I read and tried so many things but i’m not even sure i make a connection with the Cpanel server
    this is what i tried- and it says i have a connection to the server but it doesn’t display my string

    Thank you very much!

    #include
    #include
    #include
    #include
    const char server[] = “shaniru.mtacloud.co.il”;

    const char* MY_SSID = “Idok”; ///hot-spot
    const char* MY_PWD = “12345678”;

    WiFiClient client;

    void setup()
    {
    Serial.begin(115200);
    Serial.print(“Connecting to “+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    Serial.println(“going into wl connect”);

    while (WiFi.status() != WL_CONNECTED) //not connected, …waiting to connect
    {
    delay(1000);
    Serial.print(“.”);
    }
    Serial.println(“wl connected”);
    Serial.println(“”);
    Serial.println(“Credentials accepted! Connected to wifi\n “);
    Serial.println(“”);
    }

    }

    void loop() {

    // Wait a few seconds between measurements.
    delay(2000);

    //prefer to use float, but package size or float conversion isnt working
    //will revise in future with a string fuction or float conversion function
    // int IfTake=0;
    Serial.println (“IfTake”);

    Serial.println(“\nStarting connection to server…”);
    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
    Serial.println(“connected to server”);
    WiFi.printDiag(Serial);
    int ifTake= 585;
    int ido=123;
    String data = “ido=”
    + (String) ido
    + “ifTake=” +(String) ifTake;

    //change URL below if using your Sub-Domain
    client.println(“POST gettingData.php HTTP/1.1”);
    //change URL below if using your Domain
    client.print(“Host: shaniru.mtacloud.co.il\n”);
    client.println(“User-Agent: ESP8266/1.0”);
    client.println(“Connection: close”);
    client.println(“Content-Type: application/x-www-form-urlencoded”);
    client.print(“Content-Length: “);
    client.print(data.length());
    client.print(“\n\n”);
    client.print(data);
    client.stop();

    Serial.println(“\n”);
    Serial.println(“My data string im POSTing looks like this: “);
    Serial.println(data);
    Serial.println(“And it is this many bytes: “);
    Serial.println(data.length());
    delay(2000);
    }

    }

    void printWifiStatus() {
    // print the SSID of the network you’re attached to:
    Serial.print(“SSID: “);
    Serial.println(WiFi.SSID());

    // print your WiFi shield’s IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print(“IP Address: “);
    Serial.println(ip);

    // print the received signal strength:
    long rssi = WiFi.RSSI();
    Serial.print(“signal strength (RSSI):”);
    Serial.print(rssi);
    Serial.println(” dBm”);
    }

    1. Hi! You’re welcome, and thanks for the feedback 🙂

      Unfortunately I never worked with that feature with CPanel, so I cannot be of much assistance.

      Nonetheless, I can recommend some things that may help.

      First of all, are you sure that the feature of CPanel that you are trying to use is reachable by HTTP? Or does it use any other protocol?

      If it is HTTP, is it regular HTTP or is it secure HTTP (HTTPS)? If it is HTTPS, then your code should not work because it is not handling the secure related stuff, such as encryption, validating certificates, etc..

      If it is plain HTTP, then my recommendation is that you use the ESP HTTP Client API from this post. It should be less error prone than using sockets (WiFiClient is the same as using sockets).

      Also, assuming that the CPanel can be reached by HTTP, you can first try to send the request from a tool such as Postman, which is for sure a reliable HTTP client. If it also doesn’t work with postman, then most likely there is something wrong with the data that you are sending to the server or some problem with the server.
      https://www.getpostman.com/

      Hope this can help you debugging your application 🙂

      Best regards,
      Nuno Santos

  22. Hey Antepher,
    thanks for sharing with us this project!
    Im having a problem with a simple project i am trying to do, I hope you can help me-
    my MySQL DB(Cpanel server) include a table “Alerts” that have- day,hour(4 different hours 9,14,19,22),cell,status(if the button pressed). we try to light a led when the time “now” equals to the alert schedule.
    in the sending data -what i thought is that after the button is being pressed it will send 0/1 to the server to change the “status”.
    in the receiving data- i need to get the cell the day and the hour to light the button.
    I read and tried so many things but i’m not even sure i make a connection with the Cpanel server
    this is what i tried- and it says i have a connection to the server but it doesn’t display my string
    Thank you very much!
    #include
    #include
    #include
    #include
    const char server[] = “shaniru.mtacloud.co.il”;
    const char* MY_SSID = “Idok”; ///hot-spot
    const char* MY_PWD = “12345678”;
    WiFiClient client;
    void setup()
    {
    Serial.begin(115200);
    Serial.print(“Connecting to “+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    Serial.println(“going into wl connect”);
    while (WiFi.status() != WL_CONNECTED) //not connected, …waiting to connect
    {
    delay(1000);
    Serial.print(“.”);
    }
    Serial.println(“wl connected”);
    Serial.println(“”);
    Serial.println(“Credentials accepted! Connected to wifi\n “);
    Serial.println(“”);
    }
    }
    void loop() {
    // Wait a few seconds between measurements.
    delay(2000);
    //prefer to use float, but package size or float conversion isnt working
    //will revise in future with a string fuction or float conversion function
    // int IfTake=0;
    Serial.println (“IfTake”);
    Serial.println(“\nStarting connection to server…”);
    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
    Serial.println(“connected to server”);
    WiFi.printDiag(Serial);
    int ifTake= 585;
    int ido=123;
    String data = “ido=”
    + (String) ido
    + “ifTake=” +(String) ifTake;
    //change URL below if using your Sub-Domain
    client.println(“POST gettingData.php HTTP/1.1”);
    //change URL below if using your Domain
    client.print(“Host: shaniru.mtacloud.co.il\n”);
    client.println(“User-Agent: ESP8266/1.0”);
    client.println(“Connection: close”);
    client.println(“Content-Type: application/x-www-form-urlencoded”);
    client.print(“Content-Length: “);
    client.print(data.length());
    client.print(“\n\n”);
    client.print(data);
    client.stop();
    Serial.println(“\n”);
    Serial.println(“My data string im POSTing looks like this: “);
    Serial.println(data);
    Serial.println(“And it is this many bytes: “);
    Serial.println(data.length());
    delay(2000);
    }
    }
    void printWifiStatus() {
    // print the SSID of the network you’re attached to:
    Serial.print(“SSID: “);
    Serial.println(WiFi.SSID());
    // print your WiFi shield’s IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print(“IP Address: “);
    Serial.println(ip);
    // print the received signal strength:
    long rssi = WiFi.RSSI();
    Serial.print(“signal strength (RSSI):”);
    Serial.print(rssi);
    Serial.println(” dBm”);
    }

    1. Hi! You’re welcome, and thanks for the feedback 🙂
      Unfortunately I never worked with that feature with CPanel, so I cannot be of much assistance.
      Nonetheless, I can recommend some things that may help.
      First of all, are you sure that the feature of CPanel that you are trying to use is reachable by HTTP? Or does it use any other protocol?
      If it is HTTP, is it regular HTTP or is it secure HTTP (HTTPS)? If it is HTTPS, then your code should not work because it is not handling the secure related stuff, such as encryption, validating certificates, etc..
      If it is plain HTTP, then my recommendation is that you use the ESP HTTP Client API from this post. It should be less error prone than using sockets (WiFiClient is the same as using sockets).
      Also, assuming that the CPanel can be reached by HTTP, you can first try to send the request from a tool such as Postman, which is for sure a reliable HTTP client. If it also doesn’t work with postman, then most likely there is something wrong with the data that you are sending to the server or some problem with the server.
      https://www.getpostman.com/
      Hope this can help you debugging your application 🙂
      Best regards,
      Nuno Santos

  23. hello antepher,
    I have no idea about how to read the data which i send from esp8266 using php. Please give me some examples

    1. Hi!

      Sorry, unfortunately I never worked much with PHP, so I’m also not aware how to do it.

      But PHP is widely used, so I’m sure you will be able to find lots of information around the web on how to receive HTTP post requests.

      Note that receiving requests from the ESP8266 or from any other application should work the same way, so you can more easily find the PHP information you need.

      Hope this helps.

      Best regards,
      Nuno Santos

  24. hello antepher,
    I have no idea about how to read the data which i send from esp8266 using php. Please give me some examples

    1. Hi!
      Sorry, unfortunately I never worked much with PHP, so I’m also not aware how to do it.
      But PHP is widely used, so I’m sure you will be able to find lots of information around the web on how to receive HTTP post requests.
      Note that receiving requests from the ESP8266 or from any other application should work the same way, so you can more easily find the PHP information you need.
      Hope this helps.
      Best regards,
      Nuno Santos

  25. Hi antepher
    This tutorial is really interesting, I think it might be what I need , However I don’t Know how to apply it to what I need, I simply need to send the information I type on a textbox on a html webpage (I have created a server with the NodeMCU) through the server, to be displayed by the serial monitor, Would you be able to help me with that ?

    I am stuck between getting the html script variables to talk to the arduino IDE variables .

    1. Hi!

      Thank you very much for the feedback, I’m glad you found the tutorial interesting 🙂

      In that case, this tutorial won’t help you because here the ESP8266 is acting as a client, that is making a post request to a remote server.

      In your case, what you need is to setup the ESP8266 to work as a server (as you mentioned, you already set the nodemcu to work as a server).

      I’m assuming that you are serving the HTML from the ESP8266, which means that you already set up a route to serve the page.

      Additionally, you will need to setup another route to receive the content from the HTML webpage checkbox.

      So, what you need is to add is the remaining code to your HTML page so, when you fill in the text box and probably click in some button, the content of the text box is submitted to the ESP server

      So, in fact, it will be the HTML page that will do a HTTP request to your ESP8266 server (and not the other way around like you were trying to apply).

      Regarding how you do that, it pretty much depends on how you want to send the data. You can directly submit it as form data, you can use some format such as json, etc..

      I have a tutorial for the ESP32 that does something very similar to what you are trying to achieve, although you need to adapt the code for your web page needs.

      Note that the async HTTP web server library that I’m using on the ESP32 should also work on the ESP28266 with minor changes on the includes.
      https://techtutorialsx.com/2018/01/06/esp32-arduino-http-server-serving-html-and-javascript/

      Hope this helps getting you on the right path 🙂

      Best regards,
      Nuno Santos

  26. Hi antepher
    This tutorial is really interesting, I think it might be what I need , However I don’t Know how to apply it to what I need, I simply need to send the information I type on a textbox on a html webpage (I have created a server with the NodeMCU) through the server, to be displayed by the serial monitor, Would you be able to help me with that ?
    I am stuck between getting the html script variables to talk to the arduino IDE variables .

    1. Hi!
      Thank you very much for the feedback, I’m glad you found the tutorial interesting 🙂
      In that case, this tutorial won’t help you because here the ESP8266 is acting as a client, that is making a post request to a remote server.
      In your case, what you need is to setup the ESP8266 to work as a server (as you mentioned, you already set the nodemcu to work as a server).
      I’m assuming that you are serving the HTML from the ESP8266, which means that you already set up a route to serve the page.
      Additionally, you will need to setup another route to receive the content from the HTML webpage checkbox.
      So, what you need is to add is the remaining code to your HTML page so, when you fill in the text box and probably click in some button, the content of the text box is submitted to the ESP server
      So, in fact, it will be the HTML page that will do a HTTP request to your ESP8266 server (and not the other way around like you were trying to apply).
      Regarding how you do that, it pretty much depends on how you want to send the data. You can directly submit it as form data, you can use some format such as json, etc..
      I have a tutorial for the ESP32 that does something very similar to what you are trying to achieve, although you need to adapt the code for your web page needs.
      Note that the async HTTP web server library that I’m using on the ESP32 should also work on the ESP28266 with minor changes on the includes.
      https://techtutorialsx.com/2018/01/06/esp32-arduino-http-server-serving-html-and-javascript/
      Hope this helps getting you on the right path 🙂
      Best regards,
      Nuno Santos

  27. Hello!

    First of all, thanks for sharing such a good level of information, certainly is helping a lot of people,like me.

    Im working in a similary project, can you help with some problens?

    My system is basicaly like this: RFID->Arduino->Esp8266-01->MySQL->WebPage

    My only issue is sending data from esp to my web page, wich as treat and manipulate my data base them actualize the information and show in a web page.

    Could you give some light to some?

    My degree in engineering depend on this hahaha

    Thank you

    1. Hi!

      You are welcome, and thanks for the feedback, I’m very happy to know these examples are useful 🙂

      Regarding on how you “send data” to the web page, it’s important understand a couple of things before I can give a suggestion.

      Who is serving your webpage? Is your ESP8266 serving the webpage, or is another computer in the network and you want your webpage to read information from the ESP?

      Also, how frequently does your data change? Do you want it to be “real time”, or do you want to periodically ask for that information to the ESP?

      Let me know a little bit more so I can try to help 🙂

      Also, wish you good luck with your degree, I’m sure you will make it 🙂

      Best regards,
      Nuno Santos

  28. Hello!
    First of all, thanks for sharing such a good level of information, certainly is helping a lot of people,like me.
    Im working in a similary project, can you help with some problens?
    My system is basicaly like this: RFID->Arduino->Esp8266-01->MySQL->WebPage
    My only issue is sending data from esp to my web page, wich as treat and manipulate my data base them actualize the information and show in a web page.
    Could you give some light to some?
    My degree in engineering depend on this hahaha
    Thank you

    1. Hi!
      You are welcome, and thanks for the feedback, I’m very happy to know these examples are useful 🙂
      Regarding on how you “send data” to the web page, it’s important understand a couple of things before I can give a suggestion.
      Who is serving your webpage? Is your ESP8266 serving the webpage, or is another computer in the network and you want your webpage to read information from the ESP?
      Also, how frequently does your data change? Do you want it to be “real time”, or do you want to periodically ask for that information to the ESP?
      Let me know a little bit more so I can try to help 🙂
      Also, wish you good luck with your degree, I’m sure you will make it 🙂
      Best regards,
      Nuno Santos

  29. hello sir
    i have one question in my mind
    i have a code for temperature sensor with esp 8266 12 e. i set this code to take reading every 30 min
    but when i insert this code to esp it take reading every 27-28 min. i cannot understand that where is the error in code or hardware plz tell me. i can share my code also …thanks
    please reply me

    1. Hi,

      Just with the description you gave I cannot help much :/

      How does the code work? With interrupts? Delays? What is the temperature sensor?

      Best regards,
      Nuno Santos

  30. hello sir
    i have one question in my mind
    i have a code for temperature sensor with esp 8266 12 e. i set this code to take reading every 30 min
    but when i insert this code to esp it take reading every 27-28 min. i cannot understand that where is the error in code or hardware plz tell me. i can share my code also …thanks
    please reply me

    1. Hi,
      Just with the description you gave I cannot help much :/
      How does the code work? With interrupts? Delays? What is the temperature sensor?
      Best regards,
      Nuno Santos

Leave a Reply