Search code examples
phphttparduino-esp8266

Why posted data to php can be printed but not compared in if. (esp8266 only.PC web browser works correctly)


Hello when i want to compare if value send from esp8266 is same as in php or only check if this value is set, it always return false

I tried to print back these data and this works though isset say it is not set. but when i try this with pc, my code normally

if(isset($_POST['key'])){
    if($_POST['key'] == "1A2B3C4D"){
        $POWER = "";
        if($_POST['pressed'] == "1"){
            $sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
            $result = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_row($result)){
                $POWER = $row[0];
            }
            if($POWER == "OFF"){
                $POWER = "ON";
            }else{
                $POWER = "OFF";
            }
            $sql  = 'UPDATE `VolleyTest` SET `POWER`="'.$POWER.'" WHERE ID = 1';
            $conn->query($sql);     
        }
        $sql = "SELECT `POWER` FROM `VolleyTest` WHERE ID = 1";
        $result = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_row($result)){
            $POWER = $row[0];
        }
        echo $POWER;//. "  ". $_POST['pressed'] . "  " . $_POST['key'];
    }
}

esp8266:

  btn.Check();
  String state = "0";
  if(btn.Get()){
    state = "1";
  }
  HTTPClient http;    //Declare object of class HTTPClient
  btn.Check();
  String postData = "key=1A2B3C4D &pressed=" + state;//Post Data
  Serial.println(postData);
  btn.Check();
  http.begin("http://"+host+":38180/read_from_nodemcu.php");//Specify request destination
  btn.Check();
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
  btn.Check();
  int httpCode = http.POST(postData);   //Send the request
  btn.Check();
  String payload = http.getString();    //Get the response payload
  btn.Check();
  http.end();  //Close connection
  btn.Check();
  Serial.println(httpCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload

  btn.Check();

  if(httpCode == 200){
    if(payload == "ON"){
      digitalWrite(D0,HIGH);
    }else if(payload == "OFF"){
      digitalWrite(D0,LOW);
    }else {
      Serial.println("Error");
    }
  }
  btn.Check();

Solution

  • It's because of the space before & here:

    key=1A2B3C4D &pressed=
    

    This is setting $_POST['key'] to "1A2B3C4D ", which isn't equal to "1A2B3C4D". Spaces are significant when comparing strings. Change it to

    key=1A2B3C4D&pressed=
    

    if you want to ignore spaces around a string, use the trim() function.

    if(trim($_POST['key']) == "1A2B3C4D"){