php - 如何在 php 请求中获取 HTTP 响应
问题描述
我有一个cron file
运行来将图像发布到Instagram,一旦图像被发布,代码将MySQL表更新为成功。有时,如果登录到 Instagram 不成功(或)IP 被阻止,那么服务器响应会显示("status":"fail")
。如何使用(如果)读取http响应然后将MySQL更新为失败?
PHP版本:5.6.35
服务器http响应:
{“消息”:“checkpoint_required”,“checkpoint_url”:“ https://i.instagram.com/challenge/8633340132/qz34BIU1MQ/ ”,“锁定”:真,“状态”:“失败”,“错误类型”: “checkpoint_challenge_required”}
当前发布代码:
<?php
require_once("helper/functions.php");
require_once("cron_insta_include.php");
$result_outmsg = $database->query("SELECT * FROM insta_sent");
while($row_outmsg = $database->fetch_array($result_outmsg))
{
if($row_outmsg["report"] == "Scheduled")
{
$res_ch = $database->query("SELECT * FROM insta_ch WHERE serial='" . $row_outmsg["fromch"] . "'");
$row_ch = $database->fetch_array($res_ch);
if(($row_ch["status"] != "Blocked") && ($row_ch != false))
{
if((time() - $row_ch["last_used"]) > 7200)
{
try
{
//Insta Sending
$cap = "." . "\r\n\r\n" . $row_outmsg["body"] . "\r\n\r\n" . "." . "\r\n\r\n" . $row_outmsg["hash"] . "\r\n\r\n" . "." . "\r\n\r\n" . $row_outmsg["tonum"] . "\r\n\r\n" . "." . "\r\n\r\n" . time();
$obj = new InstagramUpload();
$obj->Login($row_ch["phone"], $row_ch["ch_id"]);
$obj->UploadPhoto($row_outmsg["img_lnk"], $cap);
sleep(1);
$database->query("UPDATE insta_sent SET report='Sent' WHERE serial='" . $row_outmsg["serial"] . "'");
}
catch(Exception $e)
{
$database->query("UPDATE insta_sent SET report='Failed' WHERE serial='" . $row_outmsg["serial"] . "'");
}
$sql_13 = "UPDATE insta_ch SET last_used='" . time() . "' WHERE serial='" . $row_outmsg["fromch"] . "'";
$database->query($sql_13);
}
}
else
{
//$database->query("UPDATE insta_sent SET report='Not Sent' WHERE serial='" . $row_outmsg["serial"] . "'");
}
}
}
?>
解决方案
您可以直接使用 curl 来获取 http 响应,也可以使用 guzzle http 之类的库。请参考 guzzle http 文档:http: //docs.guzzlephp.org/en/stable/
示例 curl 发布请求如下所示:
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, "your_data_array");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: "length_of_your_data_array"')
);
$result = curl_exec($ch);