PHP CURL调用SMS API出现请求超时故障求助
PHP CURL请求短信API超时问题解决
提交代码后页面直接超时,报错内容如下:
Request Timeout. This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'.
已知情况:
- 注释掉
curl_exec($ch);后页面正常加载 - 手动复制生成的URL在浏览器里能正常请求API
- PHP的CURL扩展已经启用
- 服务商确认服务器无问题,需修改代码
原代码
<html> <head> <title> sms_test </title> </head> <body> <?php $pass = "abc321"; $send = "BMSBMS"; $flash = "false"; $dest = 9994182471; //$dest = 9994182471; $senderId = "Bmstrans"; //Your message to send, Add URL encoding here. $message = ("Your login OTP is : 12345. -BMS/BHEL/TRICHY "); //Define route $route = "2"; //Prepare you post parameters $apiParams = array( 'uname' => $senderId, 'pass' => $pass, 'send' => $send, 'dest' => $dest, 'msg' => $message, ); //merge API url and parameters $apiUrl = "https://www.instaalerts.zone/SendSMS/sendmsg.php?"; foreach($apiParams as $key => $val){ $apiUrl .= $key.'='.urlencode($val).'&'; } $Url = str_replace(" ","%20",$apiUrl); echo $Url; //API call $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); curl_close($ch); ?> </body> </html>
修改后的代码
<html> <head> <title> sms_test </title> </head> <body> <?php $pass = "abc321"; $send = "BMSBMS"; $flash = "false"; $dest = 9994182471; $senderId = "Bmstrans"; $message = "Your login OTP is : 12345. -BMS/BHEL/TRICHY "; //Prepare parameters $apiParams = array( 'uname' => $senderId, 'pass' => $pass, 'send' => $send, 'dest' => $dest, 'msg' => $message, ); // 用http_build_query自动拼接参数,避免末尾多余的&,且自动处理编码 $apiUrl = "https://www.instaalerts.zone/SendSMS/sendmsg.php?" . http_build_query($apiParams); echo $apiUrl; //API call $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置连接超时(秒)和请求超时(秒) curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 15); // 禁用SSL证书验证(如果目标网站证书有问题,可选开启) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 执行请求并捕获结果和错误 $response = curl_exec($ch); if(curl_errno($ch)){ echo "<br>CURL错误:" . curl_error($ch); } curl_close($ch); // 打印API响应方便调试 echo "<br>API响应:" . $response; ?> </body> </html>
关键修改说明
- URL拼接优化:用
http_build_query()替代手动循环拼接,自动处理参数编码,还能避免URL末尾多出的&符号,消除潜在的请求异常。 - 添加超时限制:
CURLOPT_CONNECTTIMEOUT设置连接服务器的超时时间,CURLOPT_TIMEOUT设置整个请求的最大耗时,防止CURL无限等待导致页面超时。 - 错误捕获机制:通过
curl_errno()和curl_error()捕获CURL请求中的错误,方便快速定位问题。 - SSL验证调整:如果目标网站的SSL证书不被PHP信任,会导致请求卡住,关闭验证可解决此问题(生产环境建议先确认证书有效性再决定是否开启)。
- 调试输出:添加API响应打印,方便查看请求结果,辅助调试。
内容的提问来源于stack exchange,提问作者BALA MURUGAN
相关产品推荐
相关产品推荐

