PHP:在执行脚本之前等待用户输入

时间:2014-10-20 03:17:11

标签: php user-input

我有一个html输入表单以及一个php电子邮件脚本,它将这些值放在同一页面上。

问题是,在我将任何数据提交到表单之前,我收到一封空白的电子邮件,因为我的php脚本没有等待用户输入。

我不想在我的电子邮件脚本中使用另一个页面,因为我不想通过GET传递变量而我不知道如何实现会话。

谢谢,这是我的代码

<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>

<?php
if (!isset($_POST['submit'])) {
    echo 'you have hit the submit button';

    $name = $_POST['name'];
    $visitor_email = $_POST['email'];
    $message = $_POST['message'];

    $email_from = 'trustyclient@yoursite.com';
    $email_subject = "Message from client";
    $email_body = "Message from: $visitor_email \n \n Message:$message";


    $to = "myemail@myemail.com";
    $headers = "from:adam\r\n";
    mail($to,$email_subject,$email_body,$headers);
} else {
    echo 'You have not hit the submit button yet';  
}       
?>

2 个答案:

答案 0 :(得分:3)

首先,给你的提交按钮一个名字,比如'submit'(因为你已经在PHP中引用了这个名字)。例如:

<input type="submit" name="submit" value="Send Email">

现在,您可以在代码中使用$_POST['submit']

然后另一个调整:
当您说明if (!isset($_POST['submit'])) {时,如果提交按钮已按下,则会运行以下代码,因为!。要解决此问题,只需删除!,即可:

if (isset($_POST['submit'])) {
如果以下表达式!的计算结果为false,则

isset($_POST['submit'])告诉if语句求值为true。因此!表示“如果相反”。

注意:此外,按下提交按钮时PHP运行的概念稍微偏离。提交按钮会触发该页面以加载不同的页面(或同一页面)。 PHP代码只在页面加载时运行一次。

答案 1 :(得分:1)

试试这个。

<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>

</div>


<?php


if (isset($_POST['submit'])) {


echo 'you have hit the submit button';

    if (empty(trim($_POST['name'])) || empty(trim($_POST['email'])) || empty(trim($_POST['message']))) {
      echo 'Some fields are empty.';
    } else {

    $name = $_POST['name'];
    $visitor_email = $_POST['email'];
    $message = $_POST['message'];

    $email_from = 'trustyclient@yoursite.com';
    $email_subject = "Message from client";
    $email_body = "Message from: $visitor_email \n \n Message:$message";


    $to = "myemail@myemail.com";
    $headers = "from:adam\r\n";
    mail($to,$email_subject,$email_body,$headers);
    }
	} else {
	
	
	echo 'You have not hit the submit button yet';
	
	}
	
	?>

相关问题