PHP 7.4 如何通过CURL向Discord Webhook发送带崩溃日志附件的消息
解决方案
核心修改点
- 发送带附件的请求时不要手动设置
Content-Type请求头,curl会自动生成带合法边界标识的multipart/form-data头,手动设置会导致边界缺失请求解析失败 - PHP 7.4 中需要用
CURLFile类封装待上传的本地文件,不能直接传文件路径 - 携带附件时Discord webhook的参数无需json编码,直接构造关联数组:普通消息配置放在
payload_json字段中,附件放在files[N]字段中
完整可运行代码
$now = new DateTime(); $CrashFilePath = __DIR__ ."/../crashlogs/".$now->getTimestamp().".txt"; $errorLogTextFile = fopen($CrashFilePath ,"wb"); fwrite($errorLogTextFile,"errormessagehere"); fclose($errorLogTextFile); // 构造消息配置,后面放到payload_json字段中再编码 $messageConfig = [ "content" => "texthere", "username" => "nameofbot", "avatar_url" => "https://image.emojipng.com/608/12600608.jpg", "tts" => false, ]; // 构造POST请求体 $postFields = [ 'payload_json' => json_encode($messageConfig, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), // 附件字段,files[0]对应第一个附件,多个附件可依次使用files[1]、files[2]等 'files[0]' => new CURLFile($CrashFilePath, 'text/plain', basename($CrashFilePath)) ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "替换为你的Discord webhook地址"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); $response = curl_exec($ch); // 调试用代码,发送失败时可打开注释查看报错信息 // var_dump($response); // var_dump(curl_error($ch)); curl_close($ch);
验证要点
- 确认
crashlogs目录有可写权限,崩溃日志文件可以正常生成 - 替换代码中的webhook地址为你的实际Discord webhook地址
内容的提问来源于stack exchange,提问作者GreenMaskEnergy
相关产品推荐
相关产品推荐

