本篇教程讲述NodeMCU通过post方式向php服务器传递数据
esp8266 需要刷Nodemcu的固件,固件要包括http模块和开启ssl(如果服务器用http应该可以不用,用https一定要开启ssl)推荐自己从github上克隆最新版的程序自己编译。
以下代码是在nodemcu下的程序通过post请求向服务器上传和得到数据。
print(wifi.sta.getip())
wifi.setmode(wifi.STATION)
wifi.sta.config({ssid="wifi名",pwd="wifi密码"})
print(wifi.sta.getip())
function post(post_data)
http.post('https://xxx/link.php',
'Content-Type: application/x-www-form-urlencoded\r\n',
post_data,
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(data);
end
end)
end
post("device=hello&apikey=xxx");
post数据格式可以用json,json要改“Content-Type: application/x-www-form-urlencoded\r\n”这个地方。
再来说一下php服务器端。
<?php
$user = $_POST['device'];
$apikey = $_POST['apikey'];
if ($user)
{
$conn=mysqli_connect("localhost","root_sql","xxx","xxx");
mysqli_set_charset($conn, "utf8");
$result = mysqli_query($conn,"SELECT * FROM xxx WHERE Name='".xxx."'");
while($row = mysqli_fetch_array($result))
{
//xxx
}
}
else
{
echo "error100";
}
php端用变量接收nodemcu传来的数据。接下来要干的事你们自由发挥吧。其实这个方法不光可以用在nodemcu上,主要可以发post请求的设备都可以向这个平台上传数据。
通过这样的程序就可以实现一个简单的物联网平台。我还写来一个管理网站可以管理设备存储数据,过一段时间等项目完善一些我再上传代码。