Forum Moderators: coopster
The problem I'm having is that the form is generating errors when it's first loaded in the browser. The reason for this is that I'm assigning the values in the $_POST array to new variables, and if the form hasn't been submitted yet, the array is empty. So I was wondering, how do you check whether or not a form has been submitted, in order to eliminate those types of errors?
In case an example would be helpful, here's the script in question this morning. I only spent a few minutes on it and my PHP skills are less than shining, so I'm sure there are several inefficient and inelegant aspects to it. Notwithstanding, here it is:
<?phperror_reporting (E_ALL);
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];$headers = "From: $from \r\n";
$headers .= "Bcc: $from";if ($_POST['send'])
{
$status = 'E-mail Sent';
$sent = 'true';
}
else
{
$status = 'E-mail Form';
$sent = 'false';
}if ($sent = 'true')
{
mail ($to, $subject, $message, $headers);
}
else
{
// Do nothing
}?>
<html>
<head>
<title>E-mail Form</title>
</head>
<body>
<h1><?php echo $status;?></h1>
<form action="/path/to/this-script.php" method="post">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>To:</td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td>From:</td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea cols="60" rows="20" name="message"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;"><input type="submit" name="send" value="Send Message"></td>
</tr>
</table>
</form></body>
</html>
Thanks for any ideas,
Matthew
Yes, I realize this would be a severe spamming risk if I actually made the script web-accessible, but at the moment I'm just using it to hone my own skills.
However, I did find out about the empty() function, which worked great:
<?php
error_reporting (E_ALL);
if (empty($_POST))
{
$status = '<h1>E-mail Form</h1>';
}
else
{
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $from \r\n";
$headers .= "Bcc: $from";
mail ($to, $subject, $message, $headers);
$status = '<h1>E-mail Sent Successfully!</h1>';
}
?>
Even better in this case is the isset [php.net] function. There will be other time you'll want to make sure it is set and then check the value.
if (isset($_POST['variable1']) && $_POST['variable'] == 'foo')
Tim