本地测试PHP表单邮件功能遇空白页,请求技术协助
本地XAMPP环境下表单提交邮件功能故障排查
本地XAMPP的Apache与MySQL已正常运行,日志未发现异常,需求是实现表单提交时向指定邮箱发送邮件,但缺乏后端与PHP经验,无法定位问题,寻求帮助。
提供的PHP代码
文件已保存至XAMPP的htdocs文件夹:
<?php error_reporting(E_ALL); ini_set('display_errors', 1); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $email = $_POST['email']; $checkbox = implode(', ', $_POST['checkbox']); $message = $_POST['message']; // 发送表单数据邮件 $to = 'busanta29@gmail.com'; $subject = 'New Contact Form Submission'; $body = "Name: $firstName $lastName Email: $email Checkbox: $checkbox Message: $message"; $headers = "From: $email"; if (mail($to, $subject, $body, $headers)) { echo 'Message sent successfully'; } else { echo 'Error sending message'; } } ?>
React端axios提交代码
axios.post('http://localhost/mihcontactform.php', formData) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
React表单组件代码
import { useState } from 'react'; import axios from 'axios'; function ContactForm() { const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '', checkbox: [], message: '' }); const handleFormSubmit = (e) => { e.preventDefault(); const form = e.target; const formData = new FormData(form); axios.post('http://localhost/mihcontactform.php', formData) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } const handleInputChange = (e) => { if (e.target.type === 'checkbox') { let checkboxValues = formData.checkbox.slice(); if (e.target.checked) { checkboxValues.push(e.target.value); } else { checkboxValues.splice(checkboxValues.indexOf(e.target.value), 1); } setFormData({ ...formData, checkbox: checkboxValues, }); } else { setFormData({ ...formData, [e.target.name]: e.target.value, }); } }; return ( <form onSubmit={handleFormSubmit} method='POST' action='mihcontactform.php'> <label> 名字: <input type='text' name='firstName' value={formData.firstName} onChange={handleInputChange} required/> </label> <label> 姓氏: <input type='text' name='lastName' value={formData.lastName} onChange={handleInputChange} required/> </label> <label> 邮箱: <input type='email' name='email' value={formData.email} onChange={handleInputChange} required/> </label> <label> 您咨询的服务类型: <input type='checkbox' name='checkbox[]' value='A' onChange={handleInputChange} required/> A <input type='checkbox' name='checkbox[]' value='B' onChange={handleInputChange} required/> B <input type='checkbox' name='checkbox[]' value='C' onChange={handleInputChange} required/> C <input type='checkbox' name='checkbox[]' value='D' onChange={handleInputChange} required/> D </label> <label> 留言: <textarea name='message' value={formData.message} onChange={handleInputChange} required></textarea> </label> <button type='submit'>提交</button> </form> ); }
测试情况
- 直接访问
localhost/mihcontactform.php时页面空白,但包含echo "Hello World"的测试PHP文件可正常显示,说明Apache配置无问题。 - 将PHP代码中的
$_POST替换为$_GET后,出现以下错误:
内容的提问来源于stack exchange,提问作者Santa
相关产品推荐
相关产品推荐

