PHP Contact Form Not Working on Wordpress - php

I built a simple php contact form using mail(). This form has worked on my website for years.
However, I recently built a new website on wordpress. I pretty much copied and pasted the same form, however, I do not receive any email. When I hit submit, the form simply redirects to the homepage/index layout, but has the contact form url.
On the original site, however, a message is printed on a blank screen confirming the email was sent. I also tested the original code on the original site and it works.
contact_form.php:
<?php
/*
Template Name: Contact Form
`*/
include( 'header.php');
?>
<?php
if(have_posts()): while (have_posts()): the_post();
?>
<div class="wrapper">
<div class="message">
<div class="text">
<?php the_content(); ?>
<form action="contact_form_script.php" method="post">
<p>Your email address:</p> <input type="text" name="emailAddress">
<p>Subject:</p> <input type="text" name="subject">
<p>Message:</p> <textarea name="message"></textarea>
<input type="text" name="honeyPot" style="display: none;">
<br />
<input type="submit" name="email_form" value="SUBMIT"/>
</form>
<br />
<br />
</div>
</div>
</div>
<?php
endwhile;
endif;
?>
<?php
include('footer.php');
?>
contact_form_script.php
<?php
$to= 'myEmailAddress#email.com';
$from = "FROM: Email#myDomain.com";
$replyTo=$_POST['emailAddress']; /*whatever the user input*/
$headers= $from ."\r\n" .'Reply-To: '. $replyTo;
//Have also tried just $_POST['subject']; Still doesn't work
$subj="Subject: "+$_POST['subject'];
$msg=$_POST['message'];
$spam=$_POST['honeyPot'];
if (empty($spam)){
mail($to, $subj, $msg, $headers);
};
Print "Thank you for email! <br /> <br /> <a href='/'><--BACK</a>"
?>
Also, is there a better way to test a form like this to see errors or troubleshoot in some way other than just checking to see if I got the email?

There are many ways in WordPress to accomplish what you are trying to do.
Currently your form action is pointing at contact_form_script.php which assumes that this script is in the current directory. But that current directory is not relative to your contact_form.php. It is relative to the users current path. eg www.mysite.com/contact/.
One quick (but lazy) way of solving your problem would be to move contact_form_script.php into the root WordPress directory of your site. Then change the form action="/contact_form_script.php" (Note the /) causing it to post to a file called contact_form_script.php in the root site dir.
A better method would be to keep contact_form_script.php in your template directory and include it in your functions.php.
If we use the email_form submit input to let WordPress know the contact_form_script.php script needs to be loaded, this should allow you to load the whole of wordpress core and still have your custom form handling script deal with the data:
functions.php:
if (!empty($_POST['email_form'])) {
require_once(__DIR__.'/contact_form_script.php');
// You could put a die() here if you wanted the script to stop executing.
}
contact_form.php:
include( 'header.php');
if(have_posts()): while (have_posts()): the_post();
<div class="wrapper">
<div class="message">
<div class="text">
<?php the_content(); ?>
<form action="" method="post"> <!-- Notice we are now submitting our data to wordpress and not directly to our form script -->
<p>Your email address:</p> <input type="text" name="emailAddress">
<p>Subject:</p> <input type="text" name="subject">
<p>Message:</p> <textarea name="message"></textarea>
<input type="text" name="honeyPot" style="display: none;">
<br />
<input type="submit" name="email_form" value="SUBMIT"/>
</form>
<br />
<br />
</div>
</div>
</div>
Again this isn't ideal, but I suspect is what you are looking for at this point in time, and it is a step in the right direction. Keeping your code within your template.

Change the following
mail($to, $subj, $msg, $headers);
Into
wp_mail($to, $subj, $msg, $headers);
This will let WordPress properly route your mail.
Also as a whole... you should use wp_ajax to do this you can use it without writing any javascript... create a file that you include in functions with the following.
function process_contact_form() {
$to= 'myEmailAddress#email.com';
$from = "FROM: Email#myDomain.com";
$replyTo=$_POST['emailAddress']; /*whatever the user input*/
$headers= $from ."\r\n" .'Reply-To: '. $replyTo;
//Have also tried just $_POST['subject']; Still doesn't work
$subj="Subject: "+$_POST['subject'];
$msg=$_POST['message'];
$spam=$_POST['honeyPot'];
if (empty($spam)){
wp_mail($to, $subj, $msg, $headers);
};
header('Location:'.$_REQUEST['_wp_http_referer']);
wp_die();
}
add_action( 'wp_ajax_process_contact_form', 'process_contact_form' );
add_action( 'wp_ajax_nopriv_process_contact_form', 'process_contact_form' );
Change your template file to
<?php
/*
Template Name: Contact Form
`*/
include( 'header.php');
?>
<?php
if(have_posts()): while (have_posts()): the_post();
?>
<div class="wrapper">
<div class="message">
<div class="text">
<?php the_content(); ?>
<form action="<?php echo admin_url( 'admin-ajax.php' ); ?>" method="post">
<p>Your email address:</p> <input type="text" name="emailAddress">
<p>Subject:</p> <input type="text" name="subject">
<p>Message:</p> <textarea name="message"></textarea>
<?php wp_referer_field(true); ?>
<input type="hidden" name="action" value="process_contact_form">
<input type="text" name="honeyPot" style="display: none;">
<br />
<input type="submit" name="email_form" value="SUBMIT"/>
</form>
<br />
<br />
</div>
</div>
</div>
<?php
endwhile;
endif;
?>
<?php
include('footer.php');
?>

We recently faced a similar problem with our contact form. Apparently, the problem was not a result of a problem with our PHP, but rather a change in shared-hosting policies. Naturally, if you are using a VPS this would not be a problem.
However, if you have any form of shared hosting using cPanel and any form of script based email (including Contact Form 7) this can be a potential solution.
Using the "paper lantern" theme, chose the option "Registered Mail IDs" as below:
Then you should get an option to add additional email IDs. Just enter your email ID that you use in the script. In roughly around 8 hours the ID should have been propagated and you will be able to use your script.
Hope this helps! Took us a really long time to figure out.

Related

PHP 404 contact form on SPA

New to PHP-
ran through tutorials and several other threads regarding this issue and I'm struggling quite a bit. I am creating a single page application without a framework and currently running on localhost. Upon submitting the form, I am greeted with a message that says Cannot POST /mail.php
I figure I have the mail.php file in the wrong spot, so I moved it around in every single directory until I decided to just put a copy of it in EVERY directory to try and get something to work. I even posted it in the contact.js file.
contact.js
import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor() {
super();
}
async getHtml() {
return `
<div class="container">
<div class="contact">
<form action="mail.php" method="post">
<table>
<tr>
<td>
<input type="text" name="name" placeholder="Name"><br />
<input type="text" name="email" placeholder="Email"><br />
<input type="text" name="subject" placeholder="Subject"><br />
</td>
<td>
<textarea name="message" rows="5" cols="25" placeholder="Message"></textarea><br />
</td>
</tr>
</table>
<div style="float: right"><button type="submit" name="submit">Send</button> </div>
</form>
</div>
</div>
`;
}
}
mail.php
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$header = "From: ".$name."<".$email.">\r\n";
$recipient = "MYEMAIL#gmail.com";
mail($recipient, $subject, $message, $header)
or die("Error sending mail");
echo "messsage sent";
}
?>
file structure
Any help or guidance would be greatly appreciated
You need to use an HTTP server which can execute PHP programs.
You appear to have written your own server using Node.js then it won't support PHP unless you have designed it - explicitly - to do so (and you'd be better off using server-side JS instead of PHP if you were already in a Node.js ecosystem).

PHP contract form, Message Sent

I made a PHP contact form which sends an email to me.
And I would like to inform the user that the message had been sent after refreshing the page.
I was able to make a pop up only before refreshed the page, with this the problem was that if the user leaves the page before clicking ok, the message won't be sent.
This is my current code:
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$subject=$_POST['subject'];
$mailFrom=$_POST['mail'];
$message=$_POST['message'];
$mailTo = "something#something.org";
$headers = "From: ".$mailFrom;
$txt ="You have received an e-mail from".$name.".\n\n" .$message;
if ($name != '' && $mailFrom != '') {
if (mail ($mailTo, $subject, $message, $mailFrom)) {
echo '<p>Your message has been sent.</p>';
} else {
echo '<p>Something went wrong, go back and try again.</p>';
}
} else {
echo '<p>You need to fill in all required fields.</p>';
}
}
mail($mailTo,$subject,$txt,$headers);
header("Location: index.php") ;
?>
HTML:
<div class="modal-bg">
<div class="modal">
<form class="contact-form" action="contactform.php" method="post">
<h2>Contact Us!</h2>
<label for="name">Name: </label> </br>
<input type="text" name="name" placeholder="Your name"> </br>
<label for="email">E-mail</label> </br>
<input type="text" name="mail" placeholder="Your e-mail"> </br>
<label for="subject">Subject: </label> </br>
<input type="text" name="subject" placeholder="Subject"> </br>
<label for="message">Message: </label> </br>
<textarea name="message" class="message" placeholder="Message" rows="15" cols="50"></textarea> </br>
<button type="submit" name="submit"> SEND </button>
</form>
<span class="modal-close">X</span>
</div>
</div>
I used a different method. Made a PHP page which says it is successful and redirects it after 5 seconds
<html>
<head>
<meta http-equiv="refresh" content="5;URL=http://address.com">
</head>
<body>
<div id="messagesent">
<p>Message has been sent successfully<p>
<p> This page will be redirect after 5 seconds. Please wait ...<p>
</div>
</body>
</html>
Ok, so what you have there is something i have had trouble with in the past: you are redirecting with a PHP header method, which is part of a (mostly) server side language which ends all of its functions as soon as the page is loaded: what i mean by this is that the code you have there will redirect the user out of your page before alerts or messages can be given out.
What i suggest you do is a little something like this in PHP:
$alert = "this is an alert and gets set whenever something happens";
//instead of an alert you could also create the paragraph with a button which triggers the redirect.
echo
"
<script>
window.onload = function(){alert('$alert');}
//this will fire the alert and stop any other thing from happening before the alert is closed
window.location.href = "https://target_page.com";
//this redirects the user to the wanted page, NB: do use href as other methods may directly redirect without waiting for the alert to display
</script>
";
Let me know if this is what you were looking for :)

How can I upload information from a php form on a different site?

I'm creating a form that needs to upload the information retrieved to an entirely separate site.
My form's "action" is to send the information to itself in order to validate information as well as see, if the required fields are input. If no errors are found, an email is sent with a message that includes the information from the form.
My code for the index page generally looks like this:
<?php include('action_page.php'); include('config.php')?>
<form method="POST" name="email_form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-25">
<label for="subject"><span class="error">* <?php echo $titleErr;?></span> Subject <i class="glyphicon glyphicon-pencil"></i></label>
</div>
<div class="col-75">
<textarea id="subject" name="subject" placeholder="Please input a subject for the email" style="height:46px"><?php echo $title;?></textarea>
</div>
</div>
<hr>
<div class="row">
<div class="col-25">
<label for="emails"><span class="error">* <?php echo $emailErr;?>
</span> Email <i class="glyphicon glyphicon-envelope"></i></label>
</div>
<div class="col-75">
<p style="color:#0071c5">Please choose which group(s) to send this to:
</p>
<?php foreach($emails as $value): ?>
<input type="checkbox" name="email[]" value='<?php echo $value ?>'<?php if (isset($_POST['email']) && in_array($value, $_POST['email'])) echo 'checked="checked"';?> ><?php echo $value ?>&nbsp &nbsp &nbsp
<?php endforeach; ?>
</div>
</div>
My action page then sends an email using the php mail() function.
What I want to do is upload the body of the email on a separate website, which runs similarly to how Wikipedia is run - anyone can edit a page even if you're not the owner of the page.
To be honest, I'm not entirely sure how to even start. I'm able to use a header on my action page that can link my form to a different page, but this doesn't autofill like I want it to.
For example:
if(mail($mail_to, $title, $msg, implode("\r\n", $headers))){
header('Location: https://en.wikipedia.org/w/index.php?title=Japanese_aircraft_carrier_Ry%C5%ABj%C5%8D&action=edit');
}
sends the user to the appropriate Wikipedia page, but I'm not able to see any of my variables, that my form stored.
How do I solve the problem?
It's hard to say without seeing more of your code, but you will likely need API access to perform a POST request. Here is documentation from Wikipedia about working with their API in PHP.

New to PHP. Can't figure out what is missing to send mail

I'm new to PHP and having a hard time getting the PHP to mail when the contact form is filled out and submit is pressed. I've posted the PHP and HTML files. Any help is very much appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jaza Solutions - Contact</title>
<link rel = "stylesheet"
type = "text/css"
href = "jazasolutions.css" />
</head>
<body>
<div id = "header">
<img src="jazasolutions.png" alt = "Jaza Solutions, LLC">
</div>
<div id="nav">
<ul>
<li><a href=JazaSolutionsContact.html>Contact</a></li>
<li><a href=JazaSolutionsAboutUs.html>About Us</a></li>
<li><a href=JazaSolutionsCourses.html>Courses</a></li>
<li><a href=JazaSolutions.html>Home</a></li>
</ul>
</div>
<div class="sideRight">
<p> Jaza Solutions</p>
<p> 9818 Ushers Place </p>
<p> Waldorf, MD 20601 </p>
<br>
<p>301-861-2133</p>
<p>info#jazasolutions.com</p>
</div>
<div class = "main">
<p> Get the Management Certification you need to make the next step in your career! </p>
<br>
<p>SEND A MESSAGE</p>
<form class="contact-form" action="contactform.php" method="post">;
<input type="text" name="name" placeholder="Full Name">
<input type="text" name="mail" placeholder="Email">
<input type="text" name="subject" placeholder="Subject">
<textarea name="message" placeholder="Message"></textarea>
<button type="submit" name="submit">SEND MAIL</button>
</form>
</div>
</body>
</html>
The PHP code is posted here. This should send an email, but I can't figure out why it's not working.
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];
$mailTo = "pmckeown#jazasolutions.com";
$headers = "From: ".$mailFrom;
$txt = "You have received an email from ".$name.".\n\n".$message;
mail($mailTo, $subject, $txt, $headers);
header("Location: index.php?mailsend");
}
?>
I tried something similar a few years ago. After hours of searching I got a Tipp I'll never forget. The Mail RFC is so huge and has so many special cases that you don't do yourself a favor when you try to implement this on your own (Even if you get your Mail send it's most likely that it will be marked as spam from most of the Mail-Services out there because you missed some special handling or some tags). This becomes really funny when you try to send an attachment or even images in your mailer implementation. I'd recommend you try one of the proven Mail-Libraries for PHP like PHPMailer. You can expect that most of the common use-cases work out of the box without great problems.

Form redirection problem [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop form from sending email more times after initial success.
First of all, i have structured my website using directories. So basically every page is a directory and in that directory, i have a file called index.php.
I have four contact forms on my site, and at the moment, the seem to all work using the hnadler.php file. The handler file validates the data, checks the form-id posted and based on that, it routes the email appropraitely. A success message is displayed if successfully sent. However, my current implimentation is flawed in that if the user refreshes, another mail is sent. How can i solve this with my existing code? Thank you
//handler.php
<?php
if(isset($_POST['submit'])) {
//carry out validation
if(!isset($hasError)) {
//check the form id posted and set email address in $emailTo accordingly
$body = "Name: $name \n\nEmail: $email \n\nEnquiry: $enquiry";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
//index.php
<?php if(isset($hasError)) { ?>
<p class="error">Please make sure you have filled all fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p><strong>Your enquiry was sent successfully.</strong></p>
<p>Thank you for your enquiry! Your email was successfully sent and we will be in touch with you promptly.</p>
<?php }; ?>
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Enquiry form</legend>
<label for="name">Name:</label><input type="text" size="50" name="name" id="name" value="" class="required" />
<label for="email">Email:</label><input type="text" size="50" name="email" id="email" value="" class="required email" />
<label for="enquiry">Enquiry:</label><textarea rows="5" cols="20" name="enquiry" id="enquiry" class="required"></textarea>
<input type="submit" name="submit" value="Submit enquiry" class="curved-btn"></input>
<input type="hidden" id="form-id" name="form-id" value="general"></input>
</fieldset>
</form>
?>
The problem is that you aren't actually submitting to handler.php because of this:
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Change it to this:
<form id="contactform" method="post" action="handler.php">
And put your send e-mail code inside of handler.php. You will also need to put a redirect in there to get them back to a page. There are other ways to go about this, but this is how I would do it.
The browser will/can repost the data on refresh, so it will look like a new request.
A quick fix is to redirect after the form submission:
header("Location: success.php");
That way if the refresh they refresh the success page, not the page you posted to.

Categories