PHP function get checkboxes value - php

I'm currently creating a website for a local sports union, so far I have created numerous pages, one of them being a table with the members and their information. Each member has a checkbox that contains the email address as a value. I should add that at the moment the members information is viewed in members.php, but the file that gets the information (The code you can see below) is from backend file fetch.php.
What I want is that when you check multiple checkboxes and press 'Send Mail', it should open a mailto:?bcc=mail1,mail2 etc.
if(mysqli_num_rows($result))
{
echo "<form method=\"post\">";
// Printing user information etc.
echo "<td><input name=\"email[]\" type=\"checkbox\" class=\"email-cb\" value=\"$email\"></td>";
echo "<tr><td><input type=\"submit\" value=\"Send Mail\"></td></tr>";
echo "</form>"
}
First of when you press the submit button (Or Send Mail if you like), it should simply do Send Mail
I have been working on this for a while and can't seem to find a solution, anyways I came up with this method to atleast extract emails (I think this is correct).
if(isset($_POST['email']) && is_array($_POST['email']))
{
foreach($_POST['email'] as $email)
{
$emailList = "mailto:?bcc=" . implode(',', $_POST['email']);
}
}

Change $_POST['fruit'] to $_POST['email'], and you don't need the loop, because the post data is already an array.:
if(isset($_POST['email']) && is_array($_POST['email']))
{
$emailList = "mailto:?bcc=" . implode(',', $_POST['email']);
}

What does $_POST['fruit']?? Maybe you are looking for this:
if(isset($_POST['email']) && is_array($_POST['email']))
{
foreach($_POST['email'] as $email)
{
$bccList .= $email.',';
}
$emailList = "mailto:?bcc=" . $bccList;
}

Related

PHP Form processing algorithm

By way of partial explanation, my mind-set is strongly procedural, since I've been programming that way since the 60s
I'm working in PHP and trying to get my head around form handling starting with an interactive 404 error form. What I want in minimal pseudo-code is:
do {
OK = true;
display_form;
ask for optional name
ask for optional email address
ask for optional comments
on – submit{
sanitise input
validate input (which could be no input since all is optional)
if one or more inputs invalid set OK = false
}
} while (OK == false)
assemble email to webmaster using $_SERVER superglobals as well as input
send using mail function
Someone "helpfully" added curlies after the while AND at the end -- they really don't belong there -- the idea was that I wanted execution to "drop through" to those two statements only after the DO -- WHILE completed
The mail assembly could be in a separate file, or not
While this is a semi-specific problem, I'm working on the assumption that, if I can get this to work, then getting a database update working will be easier.
It seems to me that my whole conceptual algorithm is incorrect, and until I sort that I'm nowhere. I've been banging at this for a a couple of days – Google pointed at a number of semi-relevant answers here, so I'm giving it a go. The W3C examples clearly show the response code running even when there are problems with the input, which is not what I want.
The main switch you need to make here is probably the one to a request-response model of execution. You can't do a literal do..while, since you will need to send a response back to the client. The next iteration of that will be triggered by a new request to PHP, which begins again from the beginning and doesn't remember any previous state.
So, in pseudo code, it works like this:
if is POST request:
validate input, populate error variables
if input is valid:
send email with data
redirect to different page or display "thanks"
form start
for $field in fields:
output HTML for $field
maybe highlight if error
maybe set value to POSTed value to retain data
form end
So, upon the first page visit, it won't be a POST request and falls straight through to the form part. There won't be any errors or existing data, so the plain form will be output. When the form is submitted, the same code runs again and now enters the if is POST branch. If any values are invalid, it will fall through to the form again, which now can also output any error messages and existing submitted values. Only when all values are valid, will the server send an email and exit this "loop" by redirecting to another page, or maybe just outputting a "Thank you" note.
If you properly separate that into an MVC architecture, you'd have these components:
Model
data validation
email sending
View
outputs the form HTML
Controller
one for handling GET requests, just invoking the view
one for handling POST requests, essentially doing:
errors = model.validate(data)
if no errors:
model.send_email(data)
redirect()
else:
view.display_form(data, errors)
some form of router invoking the right controller based on the request URL and method
These could all be separate functions, or classes, or methods, or just files.
Below is the final code for the page. It's a basic 404 error page that may be of use to someone. And it should answer the requests that I supply the code that I was working with
It includes three files that I've not supplied:
top.php and footer.php and functions.php
top produces the HTML head statements including meta codes and also including top level banners and menu, as well as establishing the basic page format.
footer-- using the server superglobal just before the footer include, the page can provide a code update date for the page. And a consistent name and registration number for our organisation
functions.php supplies a bunch of reused functions. There are a couple of little (fairly obvious) functions in used in this code:
spacer outputs code to create an empty cell in a table.
spanCol creates a column spanning cell in a table, with the specified text and
specified tag open and close
The full page is at http://www.vfmc.org.au/notfound.php -- please don't send me too much junk email.
Code for the guts is here - I don't claim that it's brilliant, but it works thanks to help from here:
<?php
$pageTitle = "File Not Found";
$authorName = "Don Gingrich";
$styleSheet = "./css/mainstyle.css";
include_once 'top.php';
require_once "functions.php";
$indicesServer = array(
'PHP_SELF',
'HTTP_REFERER',
'SCRIPT_FILENAME',
'SCRIPT_NAME',
'REQUEST_URI',
'ORIG_PATH_INFO'
);
if (isset($_SERVER['HTTP_REFERER'])) {
$refering = $_SERVER['HTTP_REFERER'];
} else {
$refering = NULL;
}
$requested = $_SERVER['REQUEST_URI'];
// $refering = $_SERVER['HTTP_REFERER'];
if ($refering == NULL || $refering == " ") {
$refering = "referrer field was blank\n - may be due to mis-typing address\n";
}
/* basic "sanitise input" function */
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function send_webmaster_email($name, $email, $comment, $requested, $refering)
{
global $sent;
$subject = "File not Found: $requested";
$txt = "Trying to access $requested from $refering\n" . "Visitor comments follow:\n" . $comment;
if ($name != "") {
$txt .= "\n\tReporting person's name is: $name\n";
}
if ($email != "") {
$txt .= "\n\tReporting person's email is: $email\n";
}
$to = "webmaster#vfmc.org.au";
$additional_headers = "From: webmaster#vfmc.org.au\r\n";
mail($to, $subject, $txt, $additional_headers);
$sent = true;
}
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = $comment = "";
$myError = false;
global $sent;
$sent = false;
/********************************************************
* Processing code follows -- Only executed after POST
*
*******************************************************/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$requested = $_POST['requested'];
$refering = $_POST['refering'];
$requested = test_input($requested);
$refering = test_input($refering);
$myError = false;
if ($_POST["button"] == "Submit") {
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]*$/", $name)) {
$myError = true;
$nameErr = "Only letters, hyphen, and white space allowed";
}
}
if (empty($_POST["email"])) {
$email = "";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$myError = true;
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$comment = "";
} else {
$comment = test_input($_POST["comments"]);
}
if ($myError == false) {
send_webmaster_email($name, $email, $comment, $requested, $refering);
}
}
}
echo "\n";
echo "<h2>File Not Found</h2>\n";
echo "<br>\n";
echo "<br>\n";
if ($sent == true ){
echo "<h5>Email sent to Webmaster, Thank you</h5>\n";
echo "<br>Use the menu to the left or the back button<br>\n";
echo "to return to the VFMC site<br>\n";
} else {
echo " Unfortunately the file that you have asked for is unavailable.\n";
echo "<br>\n";
echo "<br>\n";
echo "This may mean that the Webmaster has forgotten to load it or the link to it is broken in some way.<br>\n";
echo "Or, if you typed a page in the browser address bar, you may have mis-typed, remember that everything<br>\n";
echo "after the <b>www.vfmc.org.au/</b> is CaSeSensitive -- FiresideFiddlers, is spelled as written.<br>\n";
echo " <br>\n";
echo " <br>\n";
echo "<h6>Please tell the webmaster by sending a message:</h6>\n";
echo " <br>\n";
echo " <br>\n";
$myFile = htmlspecialchars($_SERVER['PHP_SELF']);
echo " <form action= \"$myFile\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"refering\" value=\"$refering\" />\n";
echo "<input type=\"hidden\" name=\"requested\" value=\"$requested\" />\n";
echo " <table border=\"0\" cellpadding=\"8\" cellspacing=\"8\">\n";
echo " <colgroup>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " </colgroup>\n";
echo " <tr>\n";
spanCol("3", "Your name and email address are optional,<br> but the webmaster will be unable to respond <br>directly without them", "h5");
echo " <tr>\n";
echo " <td><label for=\"tswname\">Name</label>:</td>\n";
echo " <td><input type=\"text\" name=\"name\" id=\"tswname\" size=\"25\" /></td>\n";
echo " <td>\t";
if ($nameErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $nameErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswemail\">Email address</label>:</td>\n";
echo " <td>\n";
echo " <input type=\"text\" id=\"tswemail\" name=\"email\" size=\"25\" />\n";
echo " </td>\n";
echo " <td>\n";
if ($emailErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $emailErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswcomments\">Comments</label></td>\n";
echo " <td colspan=\"2\">\n";
echo " <textarea rows=\"15\" cols=\"45\" name=\"comments\" id=\"tswcomments\"></textarea>\n";
echo " </td>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <td align=\"center\" colspan=\"2\">\n";
echo " <input type=\"submit\" name=\"button\" value=\"Submit\" /><br>\n";
echo " </td>\n";
echo " </tr>\n";
echo " </table>\n";
echo " </form>\n";
}
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo "</td>\n";
echo "</tr>\n";
$filename = $_SERVER['SCRIPT_NAME'];
require_once "footer-code.php";
?>
</tbody>
</table> <!--PWK-EDIT END FOOTER-->
</body>
</html>

Passing php variables from php1 to php2, then having php2 return a new value assigning to variable from php1

This may sound really broken but essentially my intentions are for in php1, have a name for example validate to match a regex, if it fails to meet the conditions it will then redirect to php2 where there awaits a form where a user can retype it and submit it back to php1 where it will do the checks again. Then finally in the first php, if everything works ok it will echo it back.
Also how would i expand it so multiple things such as credit cards etc. can be validated too?
Thanks
php1
if (isset ($_POST["CardHolder"])) {
cardholder = $_POST["CardHolder"];
cardholder = sanitise_input($cardholder);
if (!preg_match("/^[a-zA-Z\s]{1,40}$/", $cardholder)) {
$errMsg .= "First name can only contain alpha characters, please re-enter";
$newcardholder = $_POST["newcardholder"];
$cardholder = $newcardholder;
}
else {
$cardholder = $_POST["CardHolder"];
}
if ($errMsg != "") {
header("Location: fix_order.php?errMsg=".$errMsg)
}
php2 (fix_order.php)
if (isset ($_GET["errMsg"])){
$cardholder = $_GET["errMsg"];
echo "<form action='process_order.php' method='post'>"
."<p><label>$cardholder:</label>"
."<input type='text' name='newcardholder'/></p>"
."<p><input type='submit' value='Submit'/>";
"</form>";
}
When calling header("Location:...") you need to give the full and absolute URL.
so header("Location: fix_order.php") will not work.

Making AJAX Call or CURL or How to send data with parameters

A company sends me a "pixel" to help me to generate a few leads.
They send me a php file like this:
http://www.blabla.com/custom.php?email=XXXXX
They need from me, to pass the email in the "email value"
The first thing i did , was, using jquery, get the values written in the inputs
...
...
and make a call to a php file that i created
$.get("http://www.example.com/catchlead.php?firstname="+$('#firstname').val()+"&correo="+$('#email').val());
and in my php there is a function:
function insertar_lead($name = NULL, $email = NULL) {
echo '<img src="http://www.blabla.com/custom.php?email='.$email.'" />';
$insert = "INSERT INTO what_i_catch (name,email) VALUES ('" . $name . "','" . $email . "')";
$GLOBALS['mysqli']->query($insert);
$GLOBALS['mysqli']->close();
}
if ($name != NULL && $email != NULL) {
insertar_lead($name, $email);
}
It inserts in my db, but is not sending the email here:
echo '<img src="http://www.blabla.com/custom.php?email='.$email.'" />';
I tried using curl, and the same hapenning,
Is AJAX the better way?
Help Me!
Thanks.,
This should work
echo "<img src=\"http://www.blabla.com/custom.php?email={$email}\">"
More approaches can be found here Examples

PHP script to remove e-mail addresses from a comma-separated list [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I run a small website and my users requested that I set up a mailing list. I found a simple free script that adds e-mail addresses to a protected text file, email.txt, in CSV format:
email1#yahoo.com,email2#yahoo.com,blah,blah,blah
The script works flawlessly. However, it is a nuisance to go through the file to manually remove e-mail addresses when users cancel their list subscriptions. I need to create a simple script that removes e-mail addresses.
All I want is a simple PHP script that displays a text box so users can enter their e-mail addresses and click a "Cancel Newsletter" button. The script should search the text file, find the given e-mail address and remove it and its trailing comma.
For example, say the contents of email.txt are
john#yahoo.com,peter#yahoo.com,steve#yahoo.com
If I type "peter#yahoo.com" into the text box displayed by my desired script, I want the file to look like this:
john#yahoo.com,steve#yahoo.com
UPDATE: I tried this code:
<?php
function showForm() {
echo '
<form method="post" action="">
Email Address: <input type="text" name="email"> <br />
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
';
}
$_POST['email']
$to_delete = 'email';
$file = array_flip(explode(",",file_get_contents("email.txt")));
unset($file[$to_delete]);
file_put_contents("email.txt",implode(",",array_flip($file));
if(!$file_put_contents) {
die('Error occured');
} else {
echo 'Your subscription has been cancelled. You will not receive any further emails from us.';
}
}
} else {
showForm();
}
?>
This code doesn't even show the form.
UPDATE 2:
Another attempt at writing this script:
<?php
$email = $_POST["email"];
$text = file_get_contents("email.txt");
$oldWord = "$email";
$newWord = "";
$text = str_replace($oldWord , $newWord , $text);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
fclose($file);
?>
This works as far as removing the e-mail address goes, but there is no announcement (echo). I would like for it to say either "that e-mail isn't subscribed" or "you have been removed," based on whether the script sucessfully finds the $email in the list and deletes it.
UPDATE 3 Dec. 31, 2011:
I tried the advanced code and just got a blank page, so I went back to my version. Here is the code I have now:
<html>
<body>
<form method="post" action="">
<p>Email Address: <input type="text" name="email"></p>
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
<?php
$email = $_POST["email"];
$basetext = file_get_contents("email.txt");
$oldWord = "$email";
$newWord = "";
$text = str_replace($oldWord , $newWord , $basetext);
$str1 = $basetext;
// echo strlen($str1);
$str2 = $text;
// echo strlen($str2);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
if ($str1 > $str2) { // This part handles the success/fail message
echo ("Success!");
} else {
echo ("Fail!");
}
fclose($file);
?>
</body>
</html>
This works perfectly. However, it displays the "fail" message when the page is loaded, not when triggered to load, after the submit button is pressed.
I would like to keep the original code if possible, just rearranged so that it only shows "Success!" or "Fail!" once it has executed the code.
I would like the echo messages to be the last script executed on the page.
Is there any reason why you don't use a database?
CREATE TABLE `emails` (`address` VARCHAR(255) NOT NULL, PRIMARY KEY (`address`)) ENGINE=InnoDB
INSERT INTO `emails` VALUES ('user1#example.com')
SELECT * FROM `emails`
DELETE FROM `emails` WHERE `address`='user1#example.com'
These are just infinitely easier and more efficient than a text file...
But if you want to use a text file...
$to_delete = 'user1#example.com';
$file = array_flip(explode(",",file_get_contents("email.txt")));
unset($file[$to_delete]);
file_put_contents("email.txt",implode(",",array_flip($file));
Basically what it does it explodes by the comma, then flips the array so that the emails are keys (and their numeric positions are values, but that doesn't matter), then it removes the email you want to delete and finally reassembles the file. The bonus of this is that it will also strip out any duplicates you may have.
You can use a similar method to add email addresses, just changing the unset line to $file['user1#example.com'] = -1; (to ensure the number doesn't conflict with anything, as that would interfere with the array flipping).
This answer was originally appended to the question body by the OP.
First I moved the form to /cancel.html and used <form action="/cancel_submit.html">.
(Where I have written .html, it is just to demonstrate, as my server is configured to use no page extentions and also so that PHP is parsed on .html pages.)
Then I put the PHP code into the page /cancel_submit.html and moved
if ($str1 > $str2) {
echo ("You Have Successfully Unsubscribed From Our Newsletter....<br>You Will Not Receive Any More Emails From Us.");
} else {
echo ("The Email Address You Specified Is Not In Our Mailing List.");
}
to another set of PHP brackets.
This meant that the e-mail adddress was sent via POST to the other page, which then performed the actual removal of the e-mail address from the list and then checked to see if an address been removed to provide the comfirmation message.
I also added two commas to $oldword = "$email"; to make it $oldword = ",$email,"; so that it only finds the text entered into the e-mail box if it has a comma on either side. This addresses the case where someone submits half of an e-mail address.
I also changed $newWord = ""; to $newWord = ","; so that if the script removes an e-mail address with commas at each side, the two e-mail addresses that were next to it will not be separated by a comma.
Here is the code I have for both pages now:
cancel.html
<p>To cancel our Newsletter please enter your email address below....</p>
<p>
<form method="post" action="/cancel_submit.html">
<p>Email Address: <input type="text" name="email"></p>
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
cancel_submit.html
<?php
$email = $_POST["email"];
$basetext = file_get_contents("email.txt");
$oldWord = ",$email,";
$newWord = ",";
$text = str_replace($oldWord , $newWord , $basetext);
$str1 = $basetext;
// echo strlen($str1);
$str2 = $text;
// echo strlen($str2);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
fclose($file);
?>
<?php
if ($str1 > $str2) {
echo ("You Have Successfully Unsubscribed From Our Newsletter....<br>You Will Not Receive Any More Emails From Us.");
} else {
echo ("The Email Address You Specified Is Not In Our Mailing List.");
}
?>
<p>
<p>Please wait to be re-directed or <u>CLICK HERE.</u>
</p>
EDIT:
I made a few improvements. I added:
$email = strtolower($email);
to both the e-mail add script and the e-mail remove script. This converted all characters entered into either form to lowercase; previously, it wouldnt remove e-mails typed in a different case than the big list had.
This messed up the confirmation message command, so I changed it to
if (str_replace($oldWord , $newWord , $basetext)) {
echo ("You Have Successfully Unsubscribed From Our Newsletter....<br>You Will Not Receive Any More Emails From Us.");
} else {
echo ("The Email Address You Specified Is Not In Our Mailing List.");
}
Suggested research:
http://us.php.net/manual/en/function.explode.php
http://us3.php.net/manual/en/function.file-put-contents.php
edited to add:
http://us3.php.net/manual/en/function.file-get-contents.php
If you end up with a 3rd party service, don't pay Aweber. Go for MailChimp. They've got a free plan if your mailing list isn't that big.
In your sample you reference a variable $_POST['email'] without assignment or testing the value. Additionally you may want to sanitize this variable.
Another issue I saw was that $to_delete = 'email';, you are only looking for entries of 'email'.
Your $file_put_contents is not being assigned.
} else { showForm(); } wasn't paired up with an if statement.
<?php
function showForm() {
echo '<form method="post" action="">' . PHP_EOL
. 'Email Address: <input type="text" name="email"> <br />' . PHP_EOL
. '<input type="submit" value="Cancel Newsletter" name="submit">' . PHP_EOL
. '</form>';
}
if($_POST['email']) {
$to_delete = $_POST['email'];
$file = array_flip(explode(",",file_get_contents("email.txt")));
unset($file[$to_delete]);
$file_put_contents = file_put_contents("email.txt",implode(",",array_flip($file));
if(!$file_put_contents) {
die('Error occured');
} else {
echo 'Your subscription has been cancelled. You will not receive any further emails from us.';
}
} else {
showForm();
}
If I understand your question correctly, this is what you are attempting to achieve.
Check to see if the user has posted from a form.
Get the email. (You should ensure that it is a sane value in this step)
Retrieve the member data.
Check to see if the user is on the list.
Remove the user and save the data if applicable.
Output the result of the function.
Display a message with form to submit to self.
I know this can be done as a very simple task, but I don't trust that approach. Additionally, I think anything interacting with permanent storage of data should have some mild to moderate form of abstraction.
I would approach that task this way.
class MailingList {
const EMAIL_OK = 1;
const ERR_EMAIL_EXISTS = -1;
const ERR_EMAIL_INVALID = -2;
const ERR_EMAIL_NOTFOUND = -3;
protected $_db_src;
protected $_db_opt;
protected $members = array(); // An array intended to hold members.
public function email_exists($email) {
return array_key_exists($this->members, $email);
}
public function remove_email($email) {
$this->_sanitize_email($email);
if ($email) {
if (array_key_exists($this->members, $email)) {
unset($this->members[$email]);
$this->_update_members();
return self::EMAIL_OK;
} else {
return self::ERR_EMAIL_NOTFOUND;
}
} else {
return self::ERR_EMAIL_INVALID;
}
}
public function add_email($email) {
$this->_sanitize_email($email);
if ($email) {
if (array_key_exists($this->members) {
return self::ERR_EMAIL_EXISTS;
} else {
$this->members[$email] = -1;
$this->_save_members();
$this->_load_members();
return self::EMAIL_OK;
}
} else {
return self::ERR_EMAIL_INVALID;
}
}
// We expect a data source and options for the
// data source upon instantiation.
// This is to prepare this class for abstraction and allow it to be
// extended to databases.
public function __construct($data_source = "flatfile", $data_options = "email.txt") {
$this->_db_src = $data_source;
$this->_db_opt = $data_options;
$this->_load_members();
}
protected function _load_members() {
// Create the function name to ensure it exists.
$data_function = "handle_" . $this->_db_src;
if (!method_exists(&$this, $this->_db_src)) {
throw new Exception('Invalid data source');
}
// Build our array of parameters to be sent to our handler function.
$parameters = array_merge(array('load'), (array) $this->_db_opt);
// This calls our data function with a load action parameter.
// This is written to expect the data function to populate $this->members.
return call_user_func_array(array(&$this, $data_function), $parameters);
}
// Most of this is similar to the constructor as far as data handling goes.
protected function _save_members() {
// Create the function name to ensure it exists.
$data_function = "handle_" . $this->_db_src;
if (!method_exists(&$this, $this->_db_src)) {
throw new Exception('Invalid data source');
}
// Set up our data options with a save action.
$parameters = array_merge(array('save'), (array) $this->_db_opt);
return call_user_func_array(array(&$this, $data_function), $parameters);
}
// The heart of the storage engine, designed for CSV data.
protected function handle_flatfile($action, $filename) {
switch ($action) {
case "load":
// Make sure we can load members.
if (!is_readable($filename)) {
throw new Exception("File: $filename, is not readable");
}
// Open our data file and load the information.
// Populate $this->members as an array just the way we expect it.
$this->members = array_flip(explode(',', file_get_contents($filename)));
break;
case "save":
// Make sure we can write to the file before we move forward.
if (!is_writeable($filename)) {
throw new Exception("File $filename, is now writable");
}
// Convert our array back to a CSV string and write it to the file.
$status = file_put_contents($filename, implode(',', array_flip($this->members)));
// If we failed to write to the file make sure something is done before we continue.
if (!$status) {
throw new Exception("Writing to file failed!");
}
break;
default:
throw new Exception("Unknown action called on data handler.");
}
}
// converts email addresses to lowercase to avoid duplication.
// should add a regex filter here to ensure that we have a valid address
protected function _sanitize_email(&$email) {
$email = strtolower($email);
}
}
function show_form() {
echo '<form method="post" action="">' . PHP_EOL
. 'Email Address: <input type="text" name="email"> <br />' . PHP_EOL
. '<input type="submit" value="Cancel Newsletter" name="submit">' . PHP_EOL
. '</form>';
}
if (isset($_POST) && isset($_POST['email'])) {
$list = new MailingList();
$status = $list->remove_email($_POST['email']);
switch ($status) {
case MalingList::EMAIL_OK:
echo "<p class='success'>Your email was successfully removed.<p>";
break;
case MailingList::ERR_EMAIL_INVALID:
echo "<p class='error'>The email address provided was invalid.</p>";
case MailingList::ERR_EMAIL_NOTFOUND:
echo "<p class='error'>The email address provided was not registered.</p>";
default:
show_form();
}
} else {
show_form();
}

Contact Forms used for years have stopped working

I posted earlier, but have more information so would like to try again. I am trying to help a friend sort out a problem with the contact forms on his web page, which is built using SiteMan. He has a basic 'contact me' form and a 'request a quote' form on his page. The page is meadowwoodpedestals.com and it is hosted on BlueHost. These forms have worked for years, but we have just discovered that he is not receiving messages being sent via these forms. Upon testing, we found that when the submit button is clicked for either of these pages, instead of getting a confirmation screen, a blank screen is displayed and no message is sent. It has been months since he made any changes in the SiteMan editor.
(1) I contacted the host for support, and the reply told me that the errors indicated a problem with the page code for these two pages:
Premature end of script headers: 500.php, referer: http://www.meadowwoodpedestals.com/content/index.php?page=quote
Premature end of script headers: 500.php, referer: http://www.meadowwoodpedestals.com/content/index.php?page=contact
The response said: As you will see, it appears that the issue is with the code itself. You will need to have your web designer, or a script specialist, look over the code for the two pages, in order to resolve these issues. (My Note: the web designer is out of business)
(2) I found the following in the Bluehost forums (this is a bluehost site), I'm not sure if it is relevant?
"The premature end of script header, on a Bluehost server, is more than likely due to CPU quota (or memory?), the script was killed due to resource limitations."
(3) I looked at the page code for the contact form, which uses method="post" action="/cgi-bin/frmctact.php" and all of the basic html looked good - I don't know javascript so I am not sure about this (I've never seen that little cross symbol before?):
<script type="text/javascript" language="javascript">
function m_sfcon (u) {
pre = "mail";
url = pre + "to:" + u;
document.location.href = url + "#meadowwoodpedestals.com";
}†</script>
(4) I looked at the page code for the quote form, which uses method="post" action="/cgi-bin/mail/mail.php", and there are no script tags at all on that page.
(5) Without posting reams of code (as I'm not sure just what is useful), here is my thinking, please let me know if this is a reasonable track:
Since there are two different pages with the same error, I'm thinking it is not really a problem in either quote.php or contact.php
The two forms use different actions, so I'm guessing it is not mail.php or frmctact.php
==> There must be something common between the two pages, but what is it?? maybe index.php?
(6) I looked at index.php, and when I clicked on the opening php tag it closed with a tag in the sixth line of this statement (the ?> just prior to 'si",):
$adress = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
include("data/page_header.php");
switch ($do) {
case "prevphp":
if ($Siteman->mlevel >= 4) {
echo preg_replace("'<\?php.*?\?>'si","",stripslashes($_POST["content"]));
}
break 1;
case "default":
if ($info[2] == 1 || $Siteman->mlevel >= $info[2]) {
include_once($content);
if ($Siteman->mlevel < 5) {
if ($page == "index") {
if (substr_count($_SERVER["HTTP_REFERER"],$adress) == 0) {
echo "<script language=\"Javascript\" type=\"text/javascript\">
var res = screen.width.toString() + 'x' + screen.height.toString();
var referer = '" . urlencode($_SERVER["HTTP_REFERER"]) . "';
document.write('<img width=\"1\" height=\"1\" src=\"stats.php?new=1&res=' + res + '&referer=' + referer + '\" id=\"stat\" name=\"stat\" />');
</script>";
}
}
}
}
break 1;
}
include("data/page_footer.php");
?>
(I don't know why this page works with address misspelled...)
Should I post the full code in cgi-bin/mail/mail.php and cgi-bin/frmctact.php to this area?
My sincere thanks for any / all help!
Abby
EDIT - Here is full frmctact.php - I deleted some blank lines and repeated warnings
<?
// ##########################################################################
//
// DynaForm v1.4 - Created by the Webligo Group
// http://www.webligo.com
//
//--> I deleted license text here
// ###########################################################################
// #### CONFIGURE FROM: ADDRESS ##############################################
// If you would like to specify the From: address of emails sent by DynaForm,
// enter it between the double quotes below. If you leave this blank, the
// server will assign the default email address.
$from_address = "info#meadowwoodpedestals.com";
// ###########################################################################
// #### ACTIVATE REQUIRED FIELDS? ############################################
//
// If you would like to make some fields of your form required, change "no" to
// "yes" below.
$required_on = "yes";
// If you have set $required_on to "yes" above, you can make fields required
// by beginning their name with "r_". For example, if you want to require
// a user to enter their name, use the following HTML:
//
// <input type='text' name='r_Name'>
//
// If a user fails to enter a required field, they will be taken to a page
// where a message such as "You have not completed all the required fields."
// will be displayed. Please specify the URL to this file below:
$required_errorpage = "/content/index.php?page=formerror";
// ###########################################################################
// #### OVERRIDE REQUIRED VARIABLES? #########################################
//NOTE: THIS WILL NOT
// AFFECT YOUR 'TURN ON REQUIRED FIELDS?' SECTION SETTINGS ABOVE.
//
// If you would like to override the three required variables in
// order to hide your email address, email subject, and thank you page
// URL from your email form, change "no" to "yes" below.
$override = "yes";
// If override is set to "yes", the hidden variables on your HTML
// email form named "rec_mailto", "rec_subject", and "rec_thanks" will be
// overridden and can therefore be removed from the form.
// If you have set override to "yes" above, you must specify new values for
// each of these variables below.
// Enter the email address(es) to send the email to.
$incoming_mailto = "info#meadowwoodpedestals.com";
// Enter the email subject.
$incoming_subject = "Website form";
// Enter the thank you page URL.
$incoming_thanks = "/content/index.php?page=formthanks";
// ###########################################################################
// #### BAN IP ADDRESSES? ####################################################
//
// If you would like to ban certain IP addresses from submitting your form,
// change "no" to "yes" below.
$ban_ip_on = "no";
// If you have set $ban_ip_on to "yes" above, please enter a list of the
// IP addresses you would like to ban, seperated only by commas.
// An example has been provided below:
$ban_ip_list = "111.222.33.55,11.33.777.99";
// ###########################################################################
// #### ACTIVATE DOMAIN SECURITY? ############################################
//
// This setting, when set to "yes" (default), will check to make sure other
// people are not submitting data to your dynaform.php file from their
// external domains. This means that if your domain name is "www.mysite.com",
// only forms on "www.mysite.com" will be able to use this dynaform.php.
// IF YOU ARE RECEIVING ERRORS SUCH AS "INVALID DOMAIN" FOR NO REASON, PLEASE
// CHANGE "yes" TO "no" BELOW.
$secure_domain_on = "no";
// ###########################################################################
// #### ACTIVATE AUTO-RESPONSE? ##############################################
//
//
// This setting, when set to "yes", will make DynaForm automatically reply to
// the user who submitted your form with an email message. If you would like
// to use this feature, change "no" to "yes" below.
$autorespond_on = "no";
// If you have set $autorespond_on to "yes" above, you must specify a subject,
// from-address, and message to include in the auto-response email.
// The following setting is the subject of the auto-response email:
$autorespond_subject = "Your Form Submission";
// The following setting is the from-address of the auto-respond email:
$autorespond_from = "youremail#yoursite.com";
// The following setting is the message of your auto-response email:
$autorespond_contents = "Your submission from our website has been received. Thank you!";
// DynaForm also needs to know how to retrieve the user's email address.
// You must specify the name of the field into which the user will enter
// their email address. For example, if your email form contains an input
// field like "<input type='text' name='Email'>" you would set the
// following setting to "Email".
$autorespond_mailto_field = "Email";
// ###########################################################################
// MAKE SURE DYNAFORM IS NOT BEING LOADED FROM THE URL
if($HTTP_SERVER_VARS['REQUEST_METHOD'] == "GET") {
echo "
<html>
<head><title>Webligo PHP DynaForm is installed correctly.</title></head>
<body>
<font style='font-family: verdana, arial; font-size: 9pt;'>
<b>DynaForm is installed correctly.</b></font><br>
<font style='font-family: verdana, arial; font-size: 8pt;'>
DynaForm Easy PHP Form Mailer was created by <a href='http://www.webligo.com'>Webligo Developments</a>.
</font>
</body></html>
";
exit();
}
// SET VARIABLES
$incoming_fields = array_keys($HTTP_POST_VARS);
$incoming_values = array_values($HTTP_POST_VARS);
if($override == "no") {
$incoming_mailto = #$HTTP_POST_VARS['rec_mailto'];
$incoming_subject = #$HTTP_POST_VARS['rec_subject'];
$incoming_thanks = #$HTTP_POST_VARS['rec_thanks'];
}
$incoming_mailto_cc = #$HTTP_POST_VARS['opt_mailto_cc'];
$incoming_mailto_bcc = #$HTTP_POST_VARS['opt_mailto_bcc'];
$form_url = #$HTTP_REFERER;
// MAKE SURE DYNAFORM IS BEING RUN FROM THE RIGHT DOMAIN
if($secure_domain_on == "yes") {
$form_url_array = parse_url($form_url);
$form_domain = $form_url_array[host];
if($form_domain != $HTTP_SERVER_VARS[HTTP_HOST]) {
echo "<h2>DynaForm Error - Invalid Domain</h2>
You have accessed DynaForm from an external domain - this is not allowed.<br>
You may only submit forms to a DynaForm file that exists on the same domain name.<br>
If you believe to be receiving this message in error, please refer to your readme.txt file.
<br><br>";
$error = "yes";
}
}
// CHECK IF MAILTO IS SET
if($incoming_mailto == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_mailto</b>\" field within the form. This field specifies who the email will
be sent to.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_mailto\" value=\"youremail#yoursite.com\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF SUBJECT IS SET
if($incoming_subject == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_subject</b>\" field within the form. This field specifies the subject of
the email that will be sent.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_subject\" value=\"New DynaForm Email\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF THANKS IS SET
if($incoming_thanks == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_thanks</b>\" field within the form. This field specifies what page the user
will be taken to after they submit the form.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_thanks\" value=\"thanks.html\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF IP ADDRESS IS BANNED
if($ban_ip_on == "yes") {
if(strstr($ban_ip_list, $HTTP_SERVER_VARS[REMOTE_ADDR])) {
echo "<h2>DynaForm Error - Banned IP</h2>
You cannot use this form because your IP address has been banned by the administrator.<br>
";
$error = "yes";
}
}
if($error == "yes") {
exit();
}
// SET EMAIL INTRODUCTION
$message = "This email was received from your DynaForm located at $form_url \n\n";
// LOAD EMAIL CONTENTS
for ($i = 0; $i < count($incoming_fields); $i++) {
if($incoming_fields[$i] != "rec_mailto") {
if($incoming_fields[$i] != "rec_subject") {
if($incoming_fields[$i] != "rec_thanks") {
if($incoming_fields[$i] != "opt_mailto_cc") {
if($incoming_fields[$i] != "opt_mailto_bcc") {
// CHECK FOR REQUIRED FIELDS IF ACTIVATED
if($required_on == "yes") {
$sub = substr($incoming_fields[$i], 0, 2);
if($sub == "r_") {
if($incoming_values[$i] == "" OR !isset($incoming_values[$i]) OR $incoming_values[$i] == " ") {
header("Location: $required_errorpage");
exit();
}}}
// ADD FIELD TO OUTGOING MESSAGE
$message .= "$incoming_fields[$i]:\n$incoming_values[$i]\n\n";
}}}}}}
// SET EMAIL FOOTER
$message .= "\n\nEnd";
// CLEAR HEADERS
$headers = "";
// ADD FROM ADDRESS
if($from_address != "") {
$headers .= "From: $from_address\r\n";
}
// CHECK FOR CC OR BCC
if($incoming_mailto_cc != "") {
$headers .= "Cc: $incoming_mailto_cc\r\n";
}
if($incoming_mailto_bcc != "") {
$headers .= "Bcc: $incoming_mailto_bcc\r\n";
}
// SEND EMAIL
mail($incoming_mailto, $incoming_subject, $message, $headers);
// SEND AUTO-RESPONSE IF ACTIVATED
if($autorespond_on == "yes") {
$autorespond_mailto = #$HTTP_POST_VARS[$autorespond_mailto_field];
$autorespond_headers = "From: $autorespond_from";
mail($autorespond_mailto, $autorespond_subject, $autorespond_contents, $autorespond_headers);
}
// FORWARD TO THANK YOU PAGE
header("Location: $incoming_thanks");
?>
The 500 errors mean PHP is crashing. You need to look in the apache error log (bluehost have an icon for this in the cpanel, IIRC), and hopefully will see some PHP error message.
[people say] "the script was killed due to resource limitations."
I don't think it is this, because the 500 error happens immediately after submitting the form.

Categories