You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Twilio API语法错误:短信发送成功但无前端确认提示

问题排查与修复方案

我来帮你梳理下代码里的问题,这些错误导致了PHP语法报错和前端无法显示确认提示:

核心错误分析

1. 中文引号引发的语法错误

你的PHP代码里多处使用了中文引号(比如‘’、« »),但PHP只能识别英文的单引号('')和双引号("")。这些非法字符会让PHP解析器混乱,这就是VS Code提示syntax error, unexpected '{'的根本原因。

比如这些错误的写法:

$sid = ‘MyAccountSID’;
'from' => ‘MyTwilioNumber’,
'body' => « MyMessage »

2. 变量名拼写错误

你定义了确认变量sms_check='OK';,但在拼接JSON时错误地使用了未定义的$email_check,这会导致输出的JSON内容无效,前端无法解析,进而出现Cannot read property 'sms_sent' of null的错误。

修正后的PHP代码

<?php 
// Required if your environment does not handle autoloading 
require __DIR__ . '/Twilio/autoload.php'; 

// Use the REST API Client to make requests to the Twilio REST API 
use Twilio\Rest\Client; 

// Your Account SID and Auth Token from twilio.com/console 
$sid = 'MyAccountSID'; 
$token = 'MyToken'; 
$client = new Client($sid, $token); 

$phone = $_POST["phone"]; 

// Use the client to do fun stuff like send text messages! 
$client->messages->create( 
    // the number you'd like to send the message to 
    $phone, 
    array( 
        // A Twilio phone number you purchased at twilio.com/console 
        'from' => 'MyTwilioNumber', 
        // the body of the text message you'd like to send 
        'body' => 'MyMessage' 
    ) 
); 

// Display a confirmation message on the screen 
$sms_check = 'OK'; 
//Use Twilio’s callback here 
$return_json = '{"sms_sent":"' . $sms_check . '"}'; 
echo $return_json; 
?>

前端代码优化建议

可以给AJAX请求添加失败处理,避免请求出错时没有提示:

$(function(){ 
    $("#frm").submit(function(e){ 
        e.preventDefault(); 
        $.post("sendnotifications.php", $("#frm").serialize(), function(data){ 
            if(data.sms_sent == 'OK'){ 
                alert("Message Sent"); 
            } else { 
                alert("Message Not Sent"); 
            } 
        }, "json")
        .fail(function() {
            alert("Request failed, please check your server setup.");
        }); 
    }); 
});

补充说明

为什么之前能成功接收短信?因为Twilio的API请求在语法错误触发前已经执行完成了,但后续的JSON输出因为变量错误和语法问题,无法返回有效的JSON数据,导致前端无法解析并显示提示。

内容的提问来源于stack exchange,提问作者Joris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:45:59