我以前从未这样做过,只需要一点建议…
我有一个index.php
文件,里面有一个简单的联系表格
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
index.php
文件的顶部有以下脚本。
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address@something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^['d'w'/+!=#|$?%{^&}*`'~-]['d'w'/'.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]'.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "'n'n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "'r'n";
$email_header .= "Content-Type: text/plain; charset=UTF-8'r'n";
$email_header .= "Reply-To: " . $EmailFrom . " 'r'n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
我现在有两个问题:
1.)当验证出错或提交邮件时成功或返回错误时,我该如何呈现/不呈现某些内容?
我知道我能做到!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
但是,$valid
在不提交表单时在页面加载时总是错误的,并且电子邮件在第一次页面加载时也总是返回错误消息。如何在提交表单时只呈现或不呈现特定的内容?
例如,当提交表单并成功返回时,我不想再呈现#contactform
了。我只想将"成功联系"打印到h1左右。
我怎样才能做到这一点?这可能很简单,我就是找不到适合自己的解决方案。
2.)当使用$_SERVER["SCRIPT_NAME"]
或PHP_SELF作为操作时,提交表单后的url将始终更改为"mydomain.com/index.PHP"。我能防止这种情况发生吗?我想提交index.php文件本身,但我不喜欢将/index.php写入url。有可能阻止这种情况发生吗?
谢谢你的帮助!
马特,
关于根据电子邮件的成功或失败打印到屏幕的第一个问题,你的检查似乎很好,但你可能不会及时收到电子邮件失败,从而将其显示到屏幕上。也就是说,您只需要将第二组代码封装在if语句中。类似这样的东西:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
至于不在表单操作中包含目录,有很多方法可以做到这一点,但这里有一种:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
然后在表单操作中使用$script。