Okay so basically i have this subscription input where people enter their email and click a button... Once they click the button the company email gets notified of the new subscriber (it receives a email and in the email states the email the user inputted)... anyways i've got it working so it does that and also writes whatever the user inputted into a .txt file.. Its all working but after i successfully got it to write to the text file, the success text after clicking the subscribe button dosent show...
HTML:
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="assets/sendmail.php" method="post">
<input type="text" name="email" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
PHP:
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'subscriptions#servready.com';
$subscriber_email = ($_POST['email']);
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body, $headers);
}
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
?>
If i remove this part of the php script, the success and invalid email text pops up:
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
Like i said, its functional, but the success text or invalid email errors and success texts don't pop up with the code that writes the persons emails to the text file.
Site is http://servready.com for testing
Per the comments above, it is the content being echoed out after echo json_encode -- the extra content breaks the JSON echoed out causing everything else to break.
http://servready.com/assets/js/scripts.js is the JS file with your countdown time in it -- it's hardcoded into the script, so that's why it starts over. You'd need to put some code in there to determine the appropriate time for the countdown to reflect. I sugget you give that a try and then post a followup question with any issues you may need assistance with.
Glad to help!
Related
I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
So I created a custom contact form in WordPress, using PHP. The form sends, and I am receiving emails. The problem I'm having is that once you hit submit, it goes to a post page, and doesn't stay on the original page.
I've tried using a session and header location (didn't work)
I also tried putting this in my action"<?php echo $_SERVER['PHP_SELF']; ?>", doesn't work either. (mail just doesn't send it and sends me to 404 page.
So I'm a little stuck, as to fix this problem. Normally I would have no problems if this was a static web page, but because I'm using WordPress, this task seems to be more troublesome.
Here is a link to the website http://www.indianpointresort.ca/
Here is the php validation:
<?php
/*session_start();
if(!isset($_SESSION['afaisfjisjfijfjiwaefjawsefijef'])){
$url = 'http://www.indianpointresort.ca/';
header("Location:home.php?url=$url");
}*/
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
echo "$name | $email | $phone | $subject | $message";
if(isset($_POST['submit'])){
$boolValidationOK = 1;
$strValidationMessage = "";
//validate first name
//validate last name
if(strlen($name)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper first and last name </br>";
}
//email validation:
$emailValidate = validate_email( $email );// calls the function below to validate the email addy
if(!$emailValidate ){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in proper email address </br>";
}
//validate phone
$phone = checkPhoneNumber($phone);
if(!$phone){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill proper phone number </br>";
}
//validate subject
if(strlen($subject)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper subject description </br>";
}
//validate description
if(strlen($message)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper message </br>";
}
if($boolValidationOK == 1){
//$strValidationMessage = "SUCCESS";
//MAIL SECURITY !!!!!!!
// WE MUST VALIDATE AGAINST EMAIL INJECTIONS; THE SPAMMERS BEST WEAPON
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
foreach($_POST as $k => $v){// change to $_POST if your form was method="post"
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
// In case of spam, all actions taken here
//header("HTTP/1.0 403 Forbidden");
echo "<script>document.location =\"http://www.bermuda-triangle.org/\" </script>";
exit; // stop all further PHP scripting, so mail will not be sent.
}
}
}
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
/* Spammer List: IP's that have spammed you before ***********/
$spams = array (
"static.16.86.46.78.clients.your-server.de",
"87.101.244.8",
"144.229.34.5",
"89.248.168.70",
"reserve.cableplus.com.cn",
"94.102.60.182",
"194.8.75.145",
"194.8.75.50",
"194.8.75.62",
"194.170.32.252"
//"S0106004005289027.ed.shawcable.net" Phil's IP as test
); // array of evil spammers
foreach ($spams as $site) {// Redirect known spammers
$pattern = "/$site/i";
if (preg_match ($pattern, $ip)) {
// whatever you want to do for the spammer
echo "logging spam activity..";
exit();
}
}
$to = "";
//$subject = " Indian Point";
// compose headers
$headers = "From: Indian Point Resort.\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$message = wordwrap($message, 70);
// send email
mail($to, $subject, $message, $headers);
}
}//end of submit
//validate phone number
function checkPhoneNumber($number){
$number = str_replace("-", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace(" ", "", $number);
$number = str_replace(",", "", $number);
$number = str_replace("(", "", $number);
$number = str_replace(")", "", $number);
if((strlen($number) != 10) || (!is_numeric($number))){
return false;
}else{
return $number;
}
}
//email validation
function validate_email( $senderemail ){ // this is a function; it receives info and returns a value.
$email = trim( $senderemail ); # removes whitespace
if(!empty($email) ):
// validate email address syntax
if( preg_match('/^[a-z0-9\_\.]+#[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
return strtolower($match[0]); # valid!
endif;
endif;
return false; # NOT valid!
}
?>
Here is the form:
<div id="msgForm" class=" msgForm five columns">
<h4>Questions?</h4>
<h5>Send us a message!</h5>
<form id="contactForm" name="contactForm" method="post" action="<?php the_permalink(); ?>">
<p><input type="text" name="name" value="<?php echo $name; ?>" placeholder="name*"/></p>
<p><input type="email" name="email" placeholder="E-mail*"/></p>
<p><input type="text" name="phone" placeholder="Phone #*"/></p>
<p><input type="text" name="subject" placeholder="subject*"/></p>
<p><textarea name="message" placeholder="Message*"></textarea></p>
<p><input type="submit" name="submit" placeholder="Submit"/></p>
<div class="error">
<?php
if($strValidationMessage){
echo $strValidationMessage;
}
?>
</div>
</form>
</div><!--end of form-->
Well, to start off I would remove that gmail account from your info (just to be safe).
Secondly I would advise you to use the sendmail scripts provided by Wordpress.
There are plugins like gravityforms which allow you to make a form and decide all these options without making a static form, nor a new template file for that matter.
You can only change to which page the form will redirect after the refresh (the action will decide that)
If you want it to stay on the same page you can put the page itself in the action and on top put an if statement like
if(isset($_POST['submit'])){
//validation, sendmail, and possibly errors here
}
else{
//show the form
}
anyway, a refreshing webform is as standard as it gets. It's just how it submits things. The only way you could prevent a page is by using jquery or javascript like so: (give your submit an id)
$('#submit').on("click", function(e){
//this prevents any submit functionality (like refresh)
e.preventDefault();
//custom code to get values here and put them in the sendmail function like so:
var message = $('$message').text();
}
Try ajax form submission. And add the insert query in a separate file.
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();
}
I got this code from a website and I have been altering it to fit my needs. The problem that I am facing is that the password reset page is not firing a new password off by php mail but instead it is refreshing the page and the user is stuck on a php include file and not the site.
I know some php but this seems to be beyond me. After 12+hrs of trying different things I am asking for help :)
I hope its an easy fix. Thanks in advance for your help and code snippets.
<?php
include 'dbc.php';
/******************* ACTIVATION BY FORM**************************/
if ($_POST['doReset']=='Reset')
{
$err = array();
$msg = array();
foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}
if(!isEmail($data['user_email'])) {
$err[] = "ERROR - Please enter a valid email";
header("Location: index.html?p=unknownuser");
}
$user_email = $data['user_email'];
//check if activ code and user is valid as precaution
$rs_check = mysql_query("select id from users where user_email='$user_email'") or die (mysql_error());
$num = mysql_num_rows($rs_check);
// Match row found with more than 1 results - the user is authenticated.
if ( $num <= 0 ) {
$err[] = "Error - Sorry no such account exists or registered.";
header("Location: index.html?p=unknownuser");
//exit();
}
if(empty($err)) {
$new_pwd = GenPwd();
$pwd_reset = PwdHash($new_pwd);
//$sha1_new = sha1($new);
//set update sha1 of new password + salt
$rs_activ = mysql_query("update users set pwd='$pwd_reset' WHERE
user_email='$user_email'") or die(mysql_error());
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
//send email
$message =
"Here are your new password details ...\n
User Email: $user_email \n
Passwd: $new_pwd \n
Thank You
Administrator
$host_upper
______________________________________________________
THIS IS AN AUTOMATED RESPONSE.
***DO NOT RESPOND TO THIS EMAIL****
";
mail($user_email, "Reset Password", $message,
"From: \"Client Password Reset\" <clientservices#example.com>\r\n" .
"X-Mailer: PHP/" . phpversion());
header("Location: index.html?p=newpassword");
exit();
}
}
/*
mail($user_email, "Reset Password", $message,
"From: \"Client Registration\" <clientservices#example.com>\r\n" .
"X-Mailer: PHP/" . phpversion());
$msg[] = "Your account password has been reset and a new password has been sent to your email address.";
//header("Location: index.html?p=newpassword");
//$msg = urlencode();
//header("Location: forgot.php?msg=$msg");
//exit();
}
}
*/
?>
<script language="JavaScript" type="text/javascript" src="jquery/jquery-1.6.4.min.js"></script>
<script language="JavaScript" type="text/javascript" src="jquery/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#actForm").validate();
});
</script>
<?php
/******************** ERROR MESSAGES*************************************************
This code is to show error messages
**************************************************************************/
if(!empty($err)) {
echo "<div class=\"msg\">";
foreach ($err as $e) {
echo "* $e <br>";
}
echo "</div>";
}
if(!empty($msg)) {
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
/******************************* END ********************************/
?><div id="clientLogin">You are about to request a reset of your client account password | Login<br>
<form action="forgot.php" method="post" name="actForm" id="actForm" style="margin-top:5px;">
Your Email <input name="user_email" type="text" class="required email" id="txtboxn" size="25"><input name="doReset" type="submit" id="doLogin3" value="Submit" class="button"></form></div>
You have:
mail($usr_email, "Reset Password", $message...);
When it looks like you should have
mail($user_email, "Reset Password", $message...);
Notice you used $usr_email instead of $user_email.
That is why no email is being sent. Then it looks like the user is redirected to index.html?p=newpassword so depending on what that page is it may appear to just be reloading the same page.
UPDATE:
Also, you have the element doReset with a value of Submit and in your PHP code you are checking to see that $_POST['doReset'] == Reset instead of Submit.
<input name="doReset" type="submit" id="doLogin3" value="Submit" class="button">
Change
if ($_POST['doReset']=='Reset')
to
if ($_POST['doReset']=='Submit')