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

使用mPDF库为网站导出的PDF文件设置自定义用户名命名

解决方案

你只需要修改代码中文件名定义的部分即可实现需求,具体调整如下:
找到代码里的$filename = md5($fname);行,替换为使用$username作为文件名主体,同时建议增加特殊字符过滤逻辑,避免非法字符导致文件名解析异常,修改后的完整代码段如下:

if (isset($_POST['pdf'])) {
    $mpdf = new \Mpdf\Mpdf();
    $body = "<h1>your details</h1>
            <strong>first name:</strong>$fname <br>
            <strong>last name:</strong>$lname <br>
            <strong>username:</strong>$username <br>
            <strong>email:</strong>$email <br>
            <strong>contact-no:</strong>$contact <br>
            <strong>date of birth:</strong>$dob <br>
            <strong>course </strong>$course <br>
            <h2>your subjects</h2> <br>
            <strong>subject 1:</strong>$sub1 <br>
            <strong>subject 2:</strong>$sub2 <br>
            <strong>subject 3:</strong>$sub3 <br>
            <strong>subject 4:</strong>$sub4 <br>
            <strong>subject 5:</strong>$sub5 <br>
            <strong>subject 6:</strong>$sub6 <br>
            <strong>subject 7:</strong>$sub7 <br>
            ";
    // 过滤文件名中Windows、Linux系统都不允许的非法字符,替换为下划线
    $filename = preg_replace('/[\/\\\:\*\?\"\<\>\|]/', '_', $username);
    $mpdf->WriteHTML($body);
    $mpdf->Output($filename.'.pdf', 'D');
}
}
} else {
    header('location:logout.php');
}
注意事项
  • 请确认$username变量在代码执行到此处前已经完成正确赋值,取值为当前操作用户的用户名
  • 增加的正则过滤逻辑可以兼容不同操作系统的文件名规则,避免下载时报错

内容的提问来源于stack exchange,提问作者Ahmed raza Idrisi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:18:02