I have a question: i need to create a POST method form with a textarea, where the user can copy-paste multiple email adressses and my form should be able to do something with each adress separately.
And i don't know how to tell to php to recognize each email adress separately from the POST value of the textarea and insert them into a table of my database for example.
so my code looks like that for the moment:
<?php
if($_POST) {
if(!empty($_POST['emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
/* Do something with each adresses ( like inserting them into a
table in my database for example) */
}
}
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>
<?php
if(!empty($_POST['Emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Do something
} else {
echo "This email adress is not valid => $email !";
return;
/* here if something else than a space or a valid email adress is inserted
the foreach will be exited and a error message specifying where
something was wrong is displayed :) */
}
}
} else {
$feedback = "Please insert one or multiple email adress(es)";
}
if(isset($feedback) and !empty($feedback)) {
echo $feedback;
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<small>Separate them with a space</small>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>
Related
I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don't know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I'm also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
<?php
// Validation function
function validation($name, $email, $message) {
$errors = [];
$final = "";
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
// Calling function
$error = validation($fname, $femail, $fmessage);
}
HTML
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?=if(isset($error)); $error : "";?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
$error = validation($fname, $femail, $fmessage); store data in variable and
isset() use to check variable exist or not
i have a working login form that shows up via button click, i can log in but it doesnt show the errors
button that shows login form with the function(in a seperate file):
<button type="button" class="btn btn-lg btn-success" name="button" onclick="signin()" id="signin">Login</button>
function signin()
{
jQuery('#login-form').css("display","block");
jQuery('#reg-form').css("display","none");
jQuery('#signin').css("display","none");
jQuery('#signup').css("display","block");
}
the modal with php(included to the file where the button is):
<?php
$email = ((isset($_POST['Email']))?$_POST['Email']:'');
$password = ((isset($_POST['Password']))?$_POST['Password']:'');
$errors = array();
?>
<div class="" id="login-form" style="display:none">
<img class="Lpic" src="img/loginpic.png">
<br>
<div class="fieldtext">
<h2 class="text-center">Login</h2>
</div>
<br>
<div>
<?php
if($_POST)
{
//form validation
if(empty($_POST['Email']) || empty($_POST['Password']))
{
$errors[] = 'Please enter email and password';
}
//check if email exists
$query = $db->query("SELECT * FROM users WHERE Email = '$email'");
$user = mysqli_fetch_assoc($query);
$userCount = mysqli_num_rows($query);
if($userCount < 1)
{
$errors[] = 'Unknown email, pleas verify';
}
if(password_verify($password, $user['Password']))
{
$errors[] = 'Password doesn\'t match, try again';
}
if(!empty($errors))
{
echo display_errors($errors);
}else{
//log user in
$user_id = $user['ID'];
login($user_id);
}
}
?>
</div>
<form action="Login.php" method="post">
<div class="inputfield">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" value="<?=$email;?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" value="<?=$password;?>">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-success btn-block">
</div>
</form>
</div>
PS: login() is a function that logs in the user, any suggestions on how to show the errors without using alert??? TIA
Well it’s definitely not the prettiest solution, but you can instead of using the display_errors() function render the form validation messages in html whenever the $errorsarray is not empty.
Something like this:
if(!empty($errors)) {
echo ‘<div id=“errors”>’;
foreach ($error in $errors) {
echo $error . “<br>”;
}
echo ‘</div>‘;
}
Sorry that i couldn’t comletely write the code, its hard to code on the phone...
I hope you get the idea.
try setting the following at the top of your php file
ini_set('display_errors', 1);
error_reporting(E_ALL);
hope this helps.
You might also want to look at this answer
I'm building a website and have I a php contact form.
Validation of the form and mail() function is working perfectly.
My php file for the form is handler.php.
Now to the problem. When I press the submit button and a error message is coming up, they comes up in a new blank page and that page is the same URL but it added /handler.php in the URL.
What i want to do is make the error messages show up under the form, and if it is no errors I want it to go to my thankyoumessage.html.
This is the php code for the form:
<?php
/*Set the mail of the reciever*/
$myemail = "mymail#example.com";
/*Display error message*/
function show_error($myError)
{
?>
<html>
<body>
<b>Var snäll och rätta till följande fel:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
/* Check inputs */
function check_input($data, $problem='error')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
// if ($problem && strlen($data) == 0)
// {
// show_error($problem);
// }
return $data;
}
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
?>
And this is the Html to the form:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control">
<label>Ditt namn</label>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate">
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control">
<label>Ämne</label>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3"></textarea>
<label>Meddelande</label>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
If you don't want to use AJAX, You can just let the mail() function process the form in the same page as the following :
<?php
// we declare empty error variables
$error = $error_email = $error_name = $error_subject = $error_message = "";
if (isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$error_email = "Email adressen är inte giltig...";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
$error_name = "Du måste skriva in ditt namn...";
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
$error_email = "Du måste skriva in din email...";
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
$error_message = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/// You can add the subject validations here as well
if (empty($_POST['subject']))
{
$error_subject = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
if(mail($myemail, $subject, $mail))
{
/// We redirect to the thank you mesage uppon a successful message sending
header("Location:thankyoumessage.html");
}
else
{
// Failure message if the mail() function failed to trigger
$error = "Something wrong !";
}
}
?>
<form class="mt-5 ml-5 mr-5" method="POST" action="" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control" required >
<label>Ditt namn</label>
</div>
<!-- Error name -->
<div class="text-center mt-4 mb-4">
<?php echo $error_name;?>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate" required>
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<!-- Error email -->
<div class="text-center mt-4 mb-4">
<?php echo $error_email;?>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control" required>
<label>Ämne</label>
</div>
<!-- Error subject -->
<div class="text-center mt-4 mb-4">
<?php echo $error_subject;?>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3" required></textarea>
<label>Meddelande</label>
</div>
<!-- Error message -->
<div class="text-center mt-4 mb-4">
<?php echo $error_message;?>
</div>
<div class="text-center mt-4 mb-4">
<?php echo $error;?>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
It sounds like you need this in a single page, but your form is directing to a second page (handler.php). You might benefit from having all of the functionality in a single script that loads both the form and handles form submission. The algorithm might go something like this:
$showForm = $showThankYou = false;
$errorMessage = '';
//if form submitted
//check for errors
//if no errors
$showThankYou = true;
//else set error vars appropriately
$errorMessage = '...';
$showForm = true;
// else
$showForm = true;
From this point, you can include both your form and your thank you wrapped in conditionals. You can include your error message in your form html, as it will be blank when the form is first loaded.
if($showForm) {
// form code block
}
if($showThankYou) {
// thank you page
}
It is going to /handler.php because is set on the form action:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
If you want to stay on the same page after form submits, you have to leave action empty. Instead, you have to set a conditional that checks if submit is set:
if(isset($_POST['submit']){
include('handler.php');
}
Adding that code below your form will execute the script when the user hits submit (you have to modify it, it has to be an not a button).
That's one way to do it using exclusively PHP. You also can put all the code of sending mail inside a function, and execute it when submit is send:
function sendMail(){
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
}
Changing the submit code
<?php
include('handler.php');
if(isset($_POST['submit'])){
sendMail();
}
?>
There are any other ways, but this two maybe solve your problem in a way that only uses PHP.
Hope it helps.
PD: You have the same ID for the name and email input.
Sounds like you need JavaScript, since the user will never leave the page. If you make handler.php return some json instead of a page, this will be super easy. First of all, I would put all your HTML in a file called contact.html so you can reference a different page from the one you're currently on. If you add an empty <p class="errorMsg"></p> to the body wherever you want, it will be invisible until there's an error.
Then you can add the below scripts in a file called submitForm.js, adding <script src="submitForm.js"></script> to the head of contact.html.
const formElement = document.querySelector('form')
const formData = new FormData(formElement)
formElement.onsubmit = event => {
event.preventDefault()
fetch('/handler.php', { method: 'POST', body: formData })
.then(response => response.json())
.then(json => {
const errorElement = document.querySelector('errorMsg')
errorElement.textContent = json.errorMsg
if (json.errorMsg !== '') document.location = '/thankyoumessage.html'
})
}
To break it down, fetch is a really easy way to make an ajax request. Your user will stay on the current page, but your code will go out to the URL and get its data for use on the current page. fetch() makes the request, and then() handles it synchronously after it gets the response. Here, I'm chaining two then()s because I need to parse it into json before I can access that data. The last then() is how you would handle the form submission.
Learn more about fetch
Fetch is a new web API that relies on ES6 features and may not be compatible with older browsers. I still encourage you to use it, because even if IE11 support is necessary, all it takes is a polyfill and a syntax converter to do all the work for you.
Now, to make fetch work like this, you'll need to put something in handler.php. You can use all the code in your first snippet, leaving out the HTML. You can return JSON just by building a string and echoing it, no html necessary. You could accomplish that by changing your show_error() function calls to assigning an $errorMsg variable, like this.
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$errorMsg = "Email adressen är inte giltig...";
}
then at the end of the file, instead of HTML you can write the JSON string like so.
echo '{ "errorMsg" : "' . $errorMsg . '" }';
Now, if your form still hit that page with an Email error for example, you would see this:
{ "errorMsg" : "Email adressen är inte giltig..." }
... Obviously you don't want to see that, but your JavaScript can see that without your user looking at it, and the JavaScript knows exactly what to do with that data, like we saw above. Then you can add as many things as you want to that JSON, so your live JavaScript can do other things with it.
Learn more about JSON
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
How can I make my thankyou text appear after form has been successfully sent?
Right now it does reappear in the form part of the page after submission but the Thankyou text doesn't appear, it worked before I put the - header('Location: index.php#contact'); but now it doesnt show up at all. My code is below:
PHP CODE
<?php
if($_POST['submit']){
if(!$_POST['name']){
$error= "<br/>-Please enter your name" ;
}
if(!$_POST['email']){
$error.= "<br/>-Please enter your email" ;
}
if (trim($_POST['message']) == "")
{
$error.= "<br/>-Please enter message";
}
if(!$_POST['contact']!=$match){
$error.= "<br/>-Please enter your contact number" ;
}
if ($error){
$result= "Whoops, error: $error";
}
else{
mail('mahdi.mashrafi#yahoo.com', "Contact message", "Name: ".$_POST['name']." Email: ".$_POST['email']."
Email: ".$_POST['name']."
Message : ".$_POST['message']."
Contact :".$_POST['contact'] );
{
$result= "Thankyou, Ill be in touch shortly";
//to get the stored
session_start()
if(isset($_SESSION["result")){
$result=$_SESSION;
}
$_SESSION["result"]=$result;
header("location:index.php#contact?result=".$result);
$result=$_GET["result"];
}
}
}
?>
HTML & PHP form
<div id="contact" >
<div class="container">
<div class="row wowload fadeInLeftBig ">
<form method = "post" action = "" id = "contact-form " class="center" role ="form">
<!--Contact Starts-->
<div >
<div class="contactform center">
<h2 class="text-center wowload fadeInUp">Tell us about your <span>Project</span></h2><br>
<?php echo $result; ?>
<div class="col-sm-6 hello">
<input type = "text" name = "name" class = "form-control" placeholer = "Your name" value = "<?php echo $_POST['name'];?>" >
</div>
<div class="col-sm-6">
<input type = "email" name = "email" class = "form-control" placeholer = "Your email" value ="<?php echo $_POST['email'];?>">
</div>
<div class="col-sm-12">
<textarea name = "message" rows = "7" class = "form-control" placeholder = "message"><?php echo $_POST['message']; ?> </textarea>
</div>
<div class="col-sm-6">
<input type="text" name="contact" placeholder="Contact" value ="<?php echo $_POST['contact'];?>">
</div>
<div class="col-sm-6">
<input type="text" name="budget" placeholder="Project Budget"></div>`
</div>
<input type = "submit" name = "submit" class = "btn btn-secondary" value = "send message"/>
</div>
</form>
</div>
</div>
</div>
UPDATE
The php code has been updated, im not sure where to place the codes given in the answer as my php knowledge isnt so good.
try this
if(mail(.......))
{
header('Location: index.php?result=Thankyou, Ill be in touch shortly');
exit();
}
index.php
if(isset($_GET['result']))
{
echo $_GET['result'];
}
What happens?
1.You set the variable $result
2.you redirect using header
Whys that wrong?
When you redirect a new php instance is opened. Your variable $result isnt set anymore.
How to solve?
1.Store the $result somewhere ( sessions for example):
//to get the stored
session_start()
if(isset($_SESSION["result")){
$result=$_SESSION;
}
//to store
$_SESSION["result"]=$result;
2.Put it into the url:
header("location:http://url#contact?result=".$result);
//access it
$result=$_GET["result"];
From past few days, I am searching for a solution in Constant Contact APIs at http://developer.constantcontact.com/libraries/sample-code.html,, but was unable to find it. So, below is our requirement.
In my website we have donations, memberships etc. When a user fills Donation form or Membership form or Contact form etc., once user submits the form, we need to send a confirmation email to user.Our requirement is, we want this email to be send from Constant Contact mail server instead of send grid or php mail server. we have already account in constant contact for sending news letters. we need to use those details foe sending confirmation emails for single user and store the email ID in our Constant Contact Account.
We need the helpful APIs to communicate in the above procedure/manner.
We didn't find any solution to send email for single donated user. how to send email to single user and message.
Current we are using third party service(Send Grid), now we would like to move to Constant Contact. We have developed this website in PHP programming language.
Kindly help us to integrate in the above procedure/manner.
Here i attached the file. i am getting error when i using the given API's and format
Below is my simple code
<?php
require_once 'Ctct/autoload.php';
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Components\EmailMarketing\Campaign;
use Ctct\Components\EmailMarketing\MessageFooter;
use Ctct\Components\EmailMarketing\Schedule;
use Ctct\Exceptions\CtctException;
// Enter your Constant Contact APIKEY and ACCESS_TOKEN
define("APIKEY", "xxxxxxxxxxxxxxxxxxxxxxxx");
define("ACCESS_TOKEN", "xxxxxxxx-xxxx-xxxx-xxxx-989939366970");
$date = date('Y-m-d H:i:s');
$cc = new ConstantContact(APIKEY);
try {
$lists = $cc->getLists(ACCESS_TOKEN);
} catch (CtctException $ex) {
foreach ($ex->getErrors() as $error) {
print_r($error);
}
}
print_r($lists);
if (isset($_POST['email']) && strlen($_POST['email']) > 1) {
$action = "Getting Contact By Email Address";
try {
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $_POST['email']);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($_POST['email']);
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of addContact defaults to false, but if this were set to true it would tell Constant
* Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact, true);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of updateContact defaults to false, but if this were set to true it would tell
* Constant Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact, true);
}
}
catch (CtctException $ex) {
echo '<span class="label label-important">Error ' . $action . '</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
function createCampaign(array $params)
{
$cc = new ConstantContact(APIKEY);
$campaign = new Campaign();
$campaign->name = $params['fname'];
$campaign->subject = "Test Mail Subject";
$campaign->from_name = $params['fname'];
$campaign->from_email = $params['email'];
//$campaign->greeting_string = $params['greeting_string'];
//$campaign->reply_to_email = $params['email'];
$campaign->text_content = $params['content_text'];
$campaign->email_content = $params['content_text'];
$campaign->email_content_format = 'HTML';
// add the selected list or lists to the campaign
$campaign->addList('venky.para#gmail.com');
return $cc->addEmailCampaign(ACCESS_TOKEN, $campaign);
}
function createSchedule($campaignId, $time)
{
$cc = new ConstantContact(APIKEY);
$schedule = new Schedule();
$schedule->scheduled_date = $time;
return $cc->addEmailCampaignSchedule(ACCESS_TOKEN, $campaignId, $schedule);
}
global $wpdb;
if(isset($_POST['submit']))
{
$fname=mysql_real_escape_string($_POST['fname']);
$useremail=mysql_real_escape_string($_POST['email']);
$content=mysql_real_escape_string($_POST['content_text']);
// attempt to create a campaign with the fields submitted, displaying any errors that occur
try {
$campaign = createCampaign($_POST);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Creating Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
// attempt to schedule a campaign with the fields submitted, displaying any errors that occur
try {
$schedule = createSchedule($campaign->id,$date);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Scheduling Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
?>
<script type="text/javascript">
function validtestmail(){
var fname=document.getElementById('fname').value;
var email=document.getElementById('email').value;
var content_text=document.getElementById('content_text').value;
if(fname=='')
{
alert('Enter Name');
document.getElementById('fname').focus();
return false;
}
else if(email=='')
{
alert('Enter Email');
document.getElementById('email').focus();
return false;
}
else if(content_text=='')
{
alert('Enter Content');
document.getElementById('content_text').focus();
return false;
}
}
</script>
<div class="container ">
<div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="innerPagesBlock fullWidth">
<div id="primary" class="col-xs-12 col-sm-12 col-md-8 col-lg-8 content-area contactbg">
<div class="myprofileHeading">Change Password </div>
<form class="form-horizontal" role="form" id="member_cp" name="member_cp" action="<?php echo get_bloginfo('home'); ?>/testmail" method="post" onsubmit="return validtestmail();" style="margin-top:30px;">
<!-- Self form start-->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 formLog">
<span style="font-size:16px; font-weight: bold; color: #FFFFFF;">
<?php
if($msg)
{?>
<div class="<?php echo $class; ?>" role="alert"><?php
echo $msg;
?>
</div><?php
}
?>
</span>
</div>
<div class="form-login formMain">
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Name:<span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="fname" name="fname" placeholder="Name" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Email: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Content: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="content_text" name="content_text" placeholder="Content" value="" >
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="submit" class="btn btn-primary btnSubmit" name="submit" id="submit">Submit</button>
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="reset" name="button2" id="button2" class="btn btn-primary btnReset">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
// Include the featured content template.
get_template_part( 'featured-content' );
}
?>
</div><!-- #main-content -->
Here how to send email to single user. How?. Is it possible?. Please help me. My time wasting from last 2 weeks.
Thanking You
You need to cast $_POST['list'] as a string. It may be posting as an integer.
Changing this:
$contact->addList($_POST['list']);
to this:
$contact->addList( (string)$_POST['list'] );
would probably do it.