ESP8266向php发送消息代码
时间: 2023-09-12 07:03:27 浏览: 98
推送php端代码
以下是一个ESP8266向PHP服务器发送POST请求的示例代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "your_PHP_server_host";
const int port = 80;
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Send a POST request to the PHP server
Serial.print("Connecting to ");
Serial.print(host);
Serial.print(":");
Serial.println(port);
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
return;
}
// Construct the POST request data
String data = "message=hello world";
// Send the POST request
client.println("POST /your_php_file.php HTTP/1.1");
client.println("Host: your_PHP_server_host");
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.println(data.length());
client.println();
client.print(data);
// Wait for the server to respond
while (client.connected()) {
if (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
Serial.println();
Serial.println("closing connection");
}
void loop() {
}
```
注意替换代码中的以下变量和值:
- ssid:WiFi网络的名称
- password:WiFi网络的密码
- host:PHP服务器的IP地址或域名
- port:PHP服务器的端口号
- data:POST请求的数据
另外,你需要在PHP服务器上创建一个接收POST请求的PHP文件,并在该文件中处理接收到的数据。
阅读全文