[英]Where to put PHP code in an HTML File (For a Contact Form)?
我有一个html文件(即index.html)。 我有联系表单的html代码(即姓名,电子邮件等。字段)。 如果可能,我应将PHP代码放在哪里而不将index.html转换为index.php文件?
如果您希望解释而不是显示php代码,则以某种方式响应对该文件的请求的http服务器必须知道这意味着开始解释该代码。 通常,使用文件扩展名.php
。
您当然可以配置您的http服务器,以便在请求.html
文件时执行相同的操作。 但这将是一个非常糟糕的方法。 不要这样
因此,将文件重命名为index.php
并继续执行。 它是最简单,透明和强大的。
如果您担心URL的外观,请查看“重写”和“漂亮的URL”,它们允许使用诸如http://my.server/index
或简单的http://my.server/
作为相同。 在http服务器内部进行重写时,请务必在内部将此类请求映射到index.php
文件,而不更改用户浏览器中可见的URL。
但是,我想在这里提到一件事,因为我经常看到初学者会遇到这样的问题:如果您的php
代码仅包含对已发布表单的处理,那么也许是验证和存储,那么绝对没有将其放入与html标记相同的文件中的原因! 相反,不要! 在将浏览器转发到另一个视图之后,请使用单独的文件进行处理。 仅当您需要将动态值插入到html标记中时,才有必要将php嵌入到标记中。 这正是php最初创建的目的,您应该通过将静态html文件转换为php文件(扩展名为.php
)来实现此目的。
实际上并不难。
1)在打开的表单标签<form action="contact-proc.php" method="post" name="contact" id="contact">
确保您有一个操作(收集数据并发送的处理页面电子邮件)。
html页面示例
<form action="contact-proc.php" method="post" name="contact" id="contact">
<table border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td colspan="2" height="5px"></td>
</tr>
<tr>
<td><div align="right"><strong><font color="#FF0000">*</font>Name:</strong></div></td>
<td><input name="name" type="text" size="35" /></td>
</tr>
<tr>
<td><div align="right"><strong><font color="#FF0000">*</font>E-Mail Address:</strong></div></td>
<td><input name="email" type="text" size="35" /></td>
</tr>
<tr>
<td><div align="right"><strong><font color="#FF0000">*</font>Message:</strong></div></td>
<td> </td>
</tr>
<tr>
<td colspan="2"><textarea name="comments" cols="50" rows="10" wrap="virtual"></textarea></td>
</tr>
<tr>
<td align="center"><div align="center"><input name="Submit" type="submit" value="Send" /></div></td>
</tr>
</table>
</form>
2)创建一个页面来处理数据并发送电子邮件。 在这种情况下, contact-proc.php
3)在处理页面上包括以下内容...
<?php
$email = 'your-email-address@domain.ext';
$domain = 'your-domain-name'; // ie: google.com
$strVisitorInfo = ''.
"Customer Service Request from Your WebSite\r\n\r\n" .
"Name : ".$_POST['name']."\r\n" .
"E-Mail : ".$_POST['email']."\r\n" .
"Comments : \r\n" .
$_POST['comments'];
$to = $Email;
$subject = "Customer Service Request from Your WebSite";
$headers = 'From: noreply@'.$domain . "\r\n" .
'Reply-To: noreply@'.$domain . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $strVisitorInfo, $headers);
?>
其中$_POST['name']
$_POST['email']
和$_POST['comments']
是html
页面上表单元素的名称。 您可以更改它们以匹配您的表单。
在处理页面上,您可以包含一些信息,以使访问者知道已经发送了电子邮件。 喜欢...
<div align="center">Thank you <?php echo $_POST['name'] ?>.<br>
Your email has been sent. We will be in touch with you soon.
</div>
当然,您将需要进行一些验证,以确保提交了空表格和其他废话。 但这是一个与这里提出的问题不同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.