PHP接收ESP8266数据代码
时间: 2023-09-23 15:10:12 浏览: 83
代码esp8266
以下是一个简单的PHP脚本,可以接收ESP8266发送的数据:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//接收POST请求
$data = file_get_contents('php://input');
//处理接收到的数据
//...
//返回响应
echo "Data received successfully!";
} else {
//返回错误信息
header('HTTP/1.1 405 Method Not Allowed');
header('Allow: POST');
echo "Only POST requests are allowed.";
}
```
在ESP8266上发送POST请求,将数据作为请求体发送到该脚本的URL上即可。例如:
```arduino
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "your_PHP_script_URL";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
String data = "Hello, PHP!"; //要发送的数据
String url = "/your_php_script.php"; //PHP脚本的URL
String request = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: " + data.length() + "\r\n" +
"Connection: close\r\n\r\n" +
data;
//连接服务器
WiFiClient client;
if (!client.connect(host, 80)) {
Serial.println("Connection failed");
return;
}
//发送请求
client.print(request);
//等待响应
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("Response:");
break;
}
}
//输出响应内容
while (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
}
//断开连接
client.stop();
}
void loop() {
}
```
以上代码演示了如何使用ESP8266发送POST请求,将字符串"Hello, PHP!"作为请求体发送到PHP脚本的URL上。PHP脚本可以通过`file_get_contents('php://input')`函数来获取请求体中的数据。
阅读全文