我正在编写一个简单的PHP订阅表单,当它运行时它什么也没做。PHP 看起来像这样:
<form class='subscribe' method='post' action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>'>
Subscribe for occasional updates and reminders!
Email: <input type='text' class='input' name='email' id='email' >
<!--There will be some type of CAPTCHA here-->
<label for='Subscribe'>
<input value='Subscribe' type='submit' id='subscribebutton' class='input' name='subscribebutton'>
</label>
<span class='error'><?php echo $inError ?> </span>
<?php
$email = '';
$inError = '';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(empty($_POST['email']))
$inError = "You must provide an email to register!";
elseif(stripos($_POST['email'],'@') !== TRUE || stripos($_POST['email'],'.') !== TRUE)
$inError = "Please provide a properly formatted email to register.";
else
{
$email = sanatizeInput($_POST['email']);
$emailFile = fopen('emails.txt','a') or die ('Sorry. Subscriptions are disabled for the time being.');
fwrite($emailFile, $email);
}
}
function sanatizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
如果我提交没有内容或格式不正确的表单,它不会抛出错误,它不是在编写文件,当我按下提交按钮时它似乎什么也没做(尽管它确实清除了字段并似乎提交了表单)。
这可能很简单,但我的眼睛完全错过了它。
任何帮助将不胜感激。
提前感谢,扎克
正确关闭表单标签,然后将 php 代码移动到页面顶部。像这样的东西,它应该有效。
<?php
$email = '';
$inError = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['email']))
$inError = "You must provide an email to register!";
elseif (stripos($_POST['email'], '@') !== TRUE || stripos($_POST['email'], '.') !== TRUE)
$inError = "Please provide a properly formatted email to register.";
else {
$email = sanatizeInput($_POST['email']);
$emailFile = fopen('emails.txt', 'a') or die('Sorry. Subscriptions are disabled for the time being.');
fwrite($emailFile, $email);
}
}
function sanatizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form class='subscribe' method='post' action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>'>
Subscribe for occasional updates and reminders!
Email: <input type='text' class='input' name='email' id='email' >
<!--There will be some type of CAPTCHA here-->
<label for='Subscribe'>
<input value='Subscribe' type='submit' id='subscribebutton' class='input' name='subscribebutton'>
</label>
<?php if(!empty($inError)){ ?><span class='error'><?php echo $inError; ?> </span> <?php } ?>
</form>