What I am trying to do is before I submit a form to Mailchimp with someones email I want to write that email to a .txt file. Mailchimp is using a "get" for the form and the "action" is run on mailchimp not the same page as form. Here is my code for the form.
<form id="subscribe-form1" action="https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff"
method="get" class="form-inline">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email address" name="EMAIL">
<div class="input-group-btn">
<button class="btn btn-grn" type="submit button" data-toggle="modal" data-target="#myModal">Sign Up</button>
</div>
</div>
<div style="visibility:collapse;" id="subscribe-result1"> </div>
<div class="checkbox">
<label>
<input type="checkbox" id="mce-group[6917]-6917-0" name="group[6917][1024]" value="1024" checked="checked" style="">
I agree to recieve FREE newsletter from Personal Trainer Food </label>
</div>
<?php //this only works if I change get->post and action ="" but then it does not submit to mail chimp.
//Get the email from POST
$email = $_REQUEST['EMAIL'];
$file = fopen("document.txt","a+");
fwrite($file,$email . "\n");
//redirect
?>
</form>
You can try appending the values manually to the URL, then redirecting to it:
▼
<form id="subscribe-form1" action="" method="get" class="form-inline">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email address" name="EMAIL">
<div class="input-group-btn">
<button class="btn btn-grn" type="submit button" data-toggle="modal" data-target="#myModal">Sign Up</button>
</div>
</div>
<div style="visibility:collapse;" id="subscribe-result1"> </div>
<div class="checkbox">
<label>
<input type="checkbox" id="mce-group[6917]-6917-0" name="group[6917][1024]" value="1024" checked="checked" style="">
I agree to recieve FREE newsletter from Personal Trainer Food </label>
</div>
<?php //this only works if I change get->post and action ="" but then it does not submit to mail chimp.
//Get the email from GET ◄■■■
$email = $_REQUEST['EMAIL'];
$file = fopen("document.txt","a+");
fwrite($file,$email . "\n"); URL PARAMETERS START
fclose($file); // ◄■■■ ▼
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email"); // ◄■■■
exit; // ◄■■■
?>
</form>
Notice the original "chimp" URL contains an ampersand $amp; as HTML symbol. I think we can get rid of it and use the "natural" ampersand &.
There is a checkbox in your form, we can add it too:
fclose($file); // ◄■■■
if ( isset( $_GET["group[6917][1024]"] ) ) // IF CHECKBOX IS CHECKED...
$chk = "&group[6917][1024]=1024"; URL PARAMETERS START
else $chk = ""; ▼
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk"); // ◄■■■
exit; // ◄■■■
The variables $email and $chk are at the end of the URL. An example of the resulting URL would be:
https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=josmanaba#yahoo.com&group[6917][1024]=1024
Edit :
Added an if to the PHP code:
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk");
exit;
}
?>
Edit #2 :
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fclose($file);
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
header("Location: https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk");
exit;
}
?>
Edit #3
Redirect with a form and auto-submit it with javascript:
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fclose($file);
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
echo "<form method='get'" .
" id='frm'" .
" target='_blank'" .
" action='https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk'>" .
"</form>" .
"<script type='text/javascript'>" .
"document.getElementById('frm').submit();" .
"</script>";
exit;
}
?>
Edit #4 :
This is edit #2 but saving the URL in the textfile :
<?php
if ( isset( $_GET["EMAIL"] ) ) {
$email = $_REQUEST['EMAIL'];
if ( isset( $_GET["group"] ) )
$chk = "&group[6917][1024]=1024";
else $chk = "";
$url = "https://personaltrainer.us6.list-manage.com/subscribe/post-json?u=4aeb5b710adef51ab754ll02f&id=76420114ff&EMAIL=$email$chk"
// SAVE EMAIL.
$file = fopen("document.txt","a");
fwrite($file,$email . "\n");
fwrite($file,$url . "\n");
fclose($file);
header("Location: $url");
exit;
}
?>
Related
Hi the following code below is my comment form. I have included this file comments.php inside my blog posts. When the user clicks submit, they are taken to the blog page rather then kept on the blog article page they are viewing.
I have used this same code for different forms throughout my website, and those pages do not redirect, but rather they stay on the same page when the user clicks submit. Which is the correct way it should be.
I am wondering why this same code on the blog page is being redirected to blog category view when user clicks submit.
How can I prevent the redirection thanks.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "First Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
//email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if (count($_POST)>0) echo "<h2>Form Submitted! Thank you <b>$name $lname</b>
for your comment</h2>";
?>
<hr>
<h3 style=" margin-top: 50px; ">Leave a comment</h3>
<h6><span class="error">* All fields required.</span></h6><br /><br />
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="text" placeholder="Name*" name="name" value="<?php echo $name;?>" required>
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
</div>
</div>
<!--Email-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="email address*" value="<?php echo $email;?>"required>
<span class="error"> <?php echo $emailErr;?></span>
<br>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" style="margin-left: 17px;" name="comment" placeholder="Enter a comment*" rows="5" cols="40" required><?php echo $comment;?></textarea>
<br><br>
<div class="g-recaptcha" data-sitekey="6Lc3ZyUUAAAAAIT2Blrg4BseJK9KFc1Rx8VDVNs-"></div><br/>
<input type="submit" name="submit" value="Submit">
</div>
<hr>
</div>
</div>
</form>
<?php
//check if the form has been submitted
if(isset($_POST['submit'])){
/* Attempt MySQL server connection. */
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
// Escape user inputs for security
$Fname = mysqli_real_escape_string($link, $_REQUEST['name']);
$Email = mysqli_real_escape_string($link, $_REQUEST['email']);
$Message = mysqli_real_escape_string($link, $_REQUEST['comment']);
// attempt insert query execution
$sql = "INSERT INTO comments (Name, Email, Comment, Approved) VALUES
('$Fname', '$Email', '$Message', '0')";
if(mysqli_query($link, $sql)){
echo "<p>$Fname Your comment will appear once approved";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<?PHP
$email = $_POST["email"];
$to = "email#email.com";
$subject = "New Email Address for Mailing List";
$headers = "From: $email\n";
$message = "A visitor to your site has posted a comment on a blog post that requires approval.\n
Email Address: $email";
$user = "$email";
$usersubject = "Thank You";
$userheaders = "From: email#email.com\n";
$usermessage = "Thank you for comment at www.oryanm.waiariki.net.nz Geyserland SBA.";
mail($to,$subject,$message,$headers);
mail($user,$usersubject,$usermessage,$userheaders);
?>
<?php
echo "<h2>Comments</h2>";
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM comments WHERE Approved=1 ORDER by id DESC";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<p><b>Comment by:</b> " . $row["Name"]. "</p>" . "<p>" .
$row["Comment"]. "</p> " . "<i><b>Posted:</b> " . $row["Posted"]. "</i><br>
<hr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Instead of php include, I used an iframe as a solution for this issue. Thanks for the help
pass one hidden field in your form
< input type="hidden" value="testRedirect">
and put redirect code on where you are redirect
and put redirect code on where you are redirect
if(isset($_REQUEST["hidden"]))
{
header('Location: http://www.example.com/your_form_view_page ');
exit;
}
My add_comment.php has a input type button with value "cancel" its not redirecting the user back to the post on which he wants to comment if he press cancel .My add comment button however works perfectly .Please advise.
<?php
require_once 'app/helper.php';
session_name('mypaperplane');
session_start();
if (!verify_client()) {
header('location: signin.php');
}
$title='Add new comment';
$error="";
if(isset($_POST['submit'])){
$comments = filter_input(INPUT_POST,'comment', FILTER_SANITIZE_STRING);
$comments = trim($comments);
$post_id = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );
$post_id = trim( $post_id );
if (! $comments) {
$error='*Comment field is required';
}else{
$com_link = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PWD, MYSQL_DB);
$uid = $_SESSION['user_id'];
$post_id = mysqli_real_escape_string( $com_link, $post_id );
$comments = mysqli_real_escape_string( $com_link, $comments );
$comsql="INSERT INTO comments VALUES('',$post_id,$uid,'$comments', NOW())";
$comresult = mysqli_query($com_link,$comsql);
if($comresult && mysqli_affected_rows($com_link)>0){
header("location:readMore.php?id=$post_id");
}else{
header("location:readMore.php?id=$post_id");
}
}
}
?>
<div class="content">
<?php include'tpl/header.php'; ?>
<form name="comment" method="post">
<label for="comment">Comment here:</label><br><br>
<textarea rows="15" cols="15" name="comment" id="comment"></textarea><br><br>
<input type="submit" name="submit" value="Add comment" onclick="window.location='readMore.php?id= <?= $post['id']; ?>';">
<input type="button" value="Cancel" onclick="window.location.href='readMore.php?id=$post_id'"><br><br>
<span class="errorB"><?= $error; ?></span>
</form>
<?php include'tpl/footer.php'; ?>
</div>
You need to put short tags around $post_id
'readMore.php?id=<?= $post_id ?>'
This started off as a pre-built contact form that came bundled in an HTML template. All of the textbox field work perfectly fine when submitting the from. However I need some help with a checkbox section I added myself. I've been trying to do some research but can't get the script to include all the selected checkboxes in the e-mail.
Here's my working html:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="include/sendemail.php" method="post">
<div class="form-process"></div>
<div class="col_half">
<label for="template-contactform-name">Name <small>*</small></label>
<input type="text" id="template-contactform-name" name="template-contactform-name" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-email">Email <small>*</small></label>
<input type="email" id="template-contactform-email" name="template-contactform-email" value="" class="required email sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_half">
<label for="template-contactform-phone">Phone <small>*</small></label>
<input type="text" id="template-contactform-phone" name="template-contactform-phone" value="" class="sm-form-control required" />
</div>
<div class="col_half col_last">
<label for="template-contactform-budget">Budget</label>
<input type="text" id="template-contactform-budget" name="template-contactform-budget" value="" class="sm-form-control" />
</div>
<div class="clear"></div>
<div class="col_full">
<label for="template-contactform-services[]">Services Required: </label>
<input name="template-contactform-services[]" type="checkbox" value="Web-Design" />Web Design
<input name="template-contactform-services[]" type="checkbox" value="E-Commerce" />E-Commerce
<input name="template-contactform-services[]" type="checkbox" value="User-Experience" />User Experience
<input name="template-contactform-services[]" type="checkbox" value="Branding" />Branding
<input name="template-contactform-services[]" type="checkbox" value="Mobile-Design" />Mobile Design
<input name="template-contactform-services[]" type="checkbox" value="Search-Marketing" />Search Marketing
</div>
<div class="col_full">
<label for="template-contactform-message">Deliverables & Goals <small>*</small></label>
<textarea class="required sm-form-control" id="template-contactform-message" name="template-contactform-message" rows="4" cols="30" placeholder="List the specific deliverables, services, and goals required..."></textarea>
</div>
<div class="col_full">
<label for="template-contactform-missing">Anything Missing?</label>
<textarea class="sm-form-control" id="template-contactform-missing" name="template-contactform-missing" rows="4" cols="30" placeholder="Is there anything else you think we should know?"></textarea>
</div>
<div class="col_full hidden">
<input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
</div>
<div class="col_full">
<!--<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="your-recaptcha-site-key"></div>-->
</div>
<div class="col_full">
<button class="button button-3d nomargin" type="submit" id="template-contactform-submit" name="template-contactform-submit" value="submit">Send Message</button>
</div>
</form>
and here's my php:
<?php
require_once('phpmailer/PHPMailerAutoload.php');
$toemails = array();
$toemails[] = array(
'email' => 'info#mydomain.com', // Your Email Address
'name' => 'Your Name' // Your Name
);
// Form Processing Messages
$message_success = 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.';
// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['template-contactform-email'] != '' ) {
$name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
$email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
$phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
$budget = isset( $_POST['template-contactform-budget'] ) ? $_POST['template-contactform-budget'] : '';
$service = isset( $_POST['template-contactform-services'] ) ? $_POST['template-contactform-services'] : '';
$message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';
$missing = isset( $_POST['template-contactform-missing'] ) ? $_POST['template-contactform-missing'] : '';
$subject = isset($subject) ? $subject : 'New Message From Contact Form';
$botcheck = $_POST['template-contactform-botcheck'];
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
foreach( $toemails as $toemail ) {
$mail->AddAddress( $toemail['email'] , $toemail['name'] );
}
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$phone = isset($phone) ? "Phone: $phone<br><br>" : '';
$budget = isset($budget) ? "Budget: $budget<br><br>" : '';
$service = isset($service) ? "Services Required: $service<br><br>" : '';
$message = isset($message) ? "Deliverables & Goals: $message<br><br>" : '';
$missing = isset($missing) ? "Anything Missing: $missing<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $phone $budget $service $message $missing $referrer";
// Runs only when File Field is present in the Contact Form
if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
$mail->IsHTML(true);
$mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
}
// Runs only when reCaptcha is present in the Contact Form
if( isset( $_POST['g-recaptcha-response'] ) ) {
$recaptcha_response = $_POST['g-recaptcha-response'];
$response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );
$g_response = json_decode( $response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
die;
}
}
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
echo '{ "alert": "success", "message": "' . $message_success . '" }';
else:
echo '{ "alert": "error", "message": "Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "Bot <strong>Detected</strong>.! Clean yourself Botster.!" }';
}
} else {
echo '{ "alert": "error", "message": "Please <strong>Fill up</strong> all the Fields and Try Again." }';
}
} else {
echo '{ "alert": "error", "message": "An <strong>unexpected error</strong> occured. Please Try Again later." }';
}
?>
Thanks in advance
You have to give different name attributes to the <input type="checkbox" /> tag. Then you can check whether a checkbox is checked with the isset() function.
After reading a number of posts on here, on how to capture the Select values in my html form, I understand the principle but I cant seem to execute it flawlessly in my code below.
$selected_val isn't being appended. perhaps its empty? What am I missing? Thanks in advance.
Desired result:
test#test.com is an A-user ,
Current result:
test#test.com is an ,
Here is how my HTML form looks:
<form method="POST" class="subscription-form form-inline id="subscribe" role="form">
<h4 class="subscription-success"><i class="icon_check"></i> Thank you for requesting... </h4>
<h4 class="subscription-error">Something Wrong!</h4>
<select name="usertype" class="form-control input-box">
<option selected value="A-user">I'm an A user</option>
<option value="B-user">I'm an B user</option>
<option value="C-user">I'm an C user</option>
</select>
<input type="email" name="email" id="subscriber-email" placeholder="Your Email" class="form-control input-box">
<button type="submit" name="submit" id="subscribe-button" class="btn btn-default standard-button">Submit</button>
</form>
Here is my php:
<?php
if ( isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
$selected_val = $_POST['usertype']; // Storing Selected Value In Variable
$e_mail = $_POST['email'] . " is a " . $selected_val . " ," . "\n";
file_put_contents('email-list.txt', $e_mail, FILE_APPEND | LOCK_EX);
}
?>
Your form is missing method attribute
Post method should be there
<form action="your.php" method="post">
<form> element should have method attribute like
<form method="POST" class="subscription-form form-inline wow fadeInRight animated" data-wow-offset="10" data-wow-duration="1.5s" id="subscribe" role="form">
And NOTE in your PHP code, the user will click the submit button so check
if ( isset($_POST['submit'])) {
selected_val = $_POST['usertype']; // Storing Selected Value In Variable
$e_mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$e_mail = $e_mail . " - is a - " .$selected_val . " ," . "\n";
file_put_contents('email-list.txt', $e_mail, FILE_APPEND | LOCK_EX);
}
I am trying to create a custom contact form page for my Wordpress theme. However on my way to finishing my codes the error message on my page won't show up.
Also, I am running on a localhost computer for testing this custom page and it seems it won't send my message to the ADMIN EMAIL that was set on my Wordpress Installation.
Here's the snippet on my WP Custom Contact Form:
<?php
/* Template Name: Contact Page */
?>
<?php
// Function for email address validation
function isEmail($verify_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|me|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",$verify_email));
}
$error_name = false;
$error_email = false;
$error_subject = false;
$error_message = false;
if (isset($_POST['submit'])) {
// Initialize the variables
$contact_name = '';
$contact_email = '';
$contact_subject = '';
$contact_message = '';
// Get the name
if (trim($_POST['contact_name']) === '') {
$error_name = true;
} else {
$name = trim($_POST['contact_name']);
}
// Get the email
if (trim($_POST['contact_email']) === '' || !isEmail($_POST['contact_email'])) {
$error_email = true;
} else {
$email = trim($_POST['contact_email']);
}
// Check if we have errors
if (!$error_name && !$error_email && !$error_subject && !$error_message) {
// Get the receiver email from the WP admin panel
$receiver_email = get_option('admin_email');
$subject = "Message from $contact_name";
$body = "You have a new quote request from $contact_name. Project details:" . PHP_EOL . PHP_EOL;
$body .= PHP_EOL . PHP_EOL;
$headers = "From: $contact_email" . PHP_EOL;
$headers .= "Reply-To: $contact_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
// If all is good, we send the email
if (mail($receiver_email, $subject, $body, $headers)) {
$email_sent = true;
} else {
$email_sent_error = true;
}
}
}
?>
<?php get_header(); ?>
<!-- BLOG AREA -->
<section>
<hr class="no-margin" />
<div class="blog-container section-content">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="box-layer custom-padding">
<div class="align-center">
<h2>We want to hear from you!</h2>
<p>If you are seeking to contact us, please fill up the form below. If you want to advertise or be partner with us just inform us on the message box below. </p>
<p>Thank you so much for your support!
<br/>We really appreciate!</p>
<?php if (isset($email_sent) && $email_sent == true) : ?>
<h2>Success!</h2>
<p>You have successfully sent the quote request. I'll get back to you as soon as possible.</p>
<?php elseif (isset($email_sent_error) && $email_sent_error == true) : ?>
<h2>There was an error!</h2>
<p>Unfortunately, there was an error while trying to send the email. Please try again.</p>
<?php else : ?>
<form action="<?php the_permalink(); ?>" method="POST" class="general-form" novalidate>
<p <?php if ($error_name) echo 'class="error"'; ?>><input name="contact_name" id="contact_name" class="form-control" placeholder="Your Name.." type="text" value="<?php if (isset($_POST['contact_name'])) echo $_POST['contact_name']; ?>" /></p>
<p <?php if ($error_email) echo 'class="error"'; ?>><input name="contact_email" id="contact_email" class="form-control" placeholder="Your Email.." type="email" value="<?php if (isset($_POST['contact_email'])) echo $_POST['contact_email']; ?>" /></p>
<p <?php if ($error_subject) echo 'class="error"'; ?>><input name="contact_subject" id="contact_subject" class="form-control" placeholder="Your Subject.." type="text" value="<?php if (isset($_POST['contact_subject'])) echo $_POST['contact_subject']; ?>"/></p>
<p <?php if ($error_message) echo 'class="error"'; ?>><textarea name="contact_message" id="contact_message" class="form-control" placeholder="Write your comment here.." rows="4" cols="100"><?php if (isset($_POST['contact_message'])) echo $_POST['contact_message']; ?></textarea></p>
<input class="btn btn-primary no-border" name="submit" type="submit" id="submit" value="Send Message">
</form>
<?php endif; ?>
</div>
</div>
<!-- RELATED ARTICLE AREA -->
</div>
<aside>
<!-- SIDEBAR AREA -->
<div class="col-md-3 col-md-offset-1 margin-sidebar">
<?php get_sidebar(); ?>
</div>
</aside>
</section>
<?php get_footer(); ?>
Any idea? or Is there a way you can correct my code if you see some errors?
To get you started
Make sure WP_DEBUG is set to true on your wp-config.php file.
You can get the last errors from mail() (answered here)
Use wordpress' functions if available, in this case wp_mail is at your disposal.
There are wordpress plugins such as gravity forms or contact form 7 which can accomplish the task.
Use filters and actions.
Had to post as an answer, couldn't comment yet.
HTH
If you would like to get the admin email address, you have to do it with:
$bloginfo = get_bloginfo( 'admin_email' );
get_option('admin_email') is only works when you save anything to that in the Theme Setup, probably it is empty now.
By the way, you can find many of professional, ready to use solution, like WordPress Contact Form Slider
<?php
/*
Plugin Name:Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'form/form.php');
include( MY_PLUGIN_PATH . 'admin/admin-menu.php');
include( MY_PLUGIN_PATH . 'database/table.php');
?>
Form.php
====================
<?php
function form()
{
echo '<form action="'.esc_url($_SERVER['REQUEST_URI']).'" method="post">';
echo '<p>';
echo 'Your First Name:';
echo '<br/>';
echo '<input type="text" name="fname" required/>';
echo '<br/>';
echo 'your Email-Id:';
echo '<br/>';
echo '<input type="email" name="email" required/>';
echo '<br/>';
echo 'Your Subject:';
echo '<br/>';
echo '<input type="text" name="subject" required/>';
echo '<br/>';
echo 'Your Message:';
echo '<br/>';
echo '<textarea name="message" cols="30" rows="4" required></textarea>';
echo '<br/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
}
if(isset($_REQUEST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$subject=$_POST['subject'];
$msg=$_POST['message'];
function insertuser($name,$email,$msg,$subject){
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$wpdb->insert($table_name, array('name' => $name, 'email' => $email , 'message'=> $msg , 'subject' => $subject) );
}
insertuser($name,$email,$msg,$subject);
}
function shortcode()
{
form();
}
add_shortcode('contact-form','shortcode');
?>
table.php
===================
<?php
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$charset_collate = $wpdb->get_charset_collate();
if( $wpdb->get_var ('SHOW TABLE LINK' .$table_name) != $table_name )
{
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(40) NOT NULL,
message text NOT NULL,
subject text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>