Debugging PHP email form - php

I have been trying to set up a simple form on my website that sends an email to my inbox (not the website visitor's) with email address that the visitor enters into the form. It isn't very complicated, but as I am testing, I can't seem to get any email address to work. I don't get any error message either. I will paste the code below.
At the very least, I'd like to know if there could be a problem with the DNS or host configurations. This is my first time building a website, so I'm unsure if the problem is in the code, the HTML (a separate file not pasted here), or the server or host settings.
To make matters more difficult, I have once gotten an error message along the lines of something not configured properly, but I can't seem to get the error message anymore. I don't think I changed any code. That makes me suspect there may be something else going on server-side. Is that feasible?
Thanks in advance for taking a peek.
<?php
$to = "MyEmailInbox#gmail.com";
$from = "mail#example.com";
$headers = "From: " . $from . "\r\n";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo 'You will be notified on <b> ' . $_POST['email'] . '</b> :)';
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
As far as the index.html is concerned, I have a single form next to a Send button. The form presumably takes the user information, filters nonsense out, and then the Send button calls the PHP script. Please find the relevant index.html code below:
<!-- SIGN UP SECTION ############################################### -->
<section id="signup">
<div class="row">
<!-- Title -->
<div class="seven columns centered">
<h2>Sign up to receive our newsletter!</h2>
<!-- Begin the Form -->
<form action="form_sender.php" method="post">
<!-- Input of E-Mail -->
<div class="eight columns">
<input name="email" class="email" type="text" placeholder="YOUR E-MAIL PLEASE ?">
</div>
<!-- Send Button -->
<div class="four columns">
<button name="send" type="submit" class="submit">SEND</button>
</div>
<!-- End of the Form -->
</form>
</div>
<!-- Text Promise we do not spam -->
<div class="twelve columns centered">
<p class="spam">We do not spam.</p>
</div>
</div>
</section>

If you are getting your $_POST variables right, which you can check using "echo", i dont think there is any bug in your code i tried your code without the &_POST vars an it worked fine.
I presume you are using wamp or xampp and testing this on your local system.
Upload the code on webserver and everything will be fine.

Related

Can I use action='POST' to PHP from contact form in React JS?

I have tried to post form data from a React JS rendered form, calling aq php file with the action part of the form... I have uploaded the form and the attached PHP file to my website, but when the form is filled out out submitted, no email is sent, and the url changes back to the homepage with the name of the PHP file tagged on (index.js/contact.php).
Is my code below bad?
Or is this just not possible to do using a combination of React JS and PHP?
contactMe.js
import React, { Component } from 'react';
class ContactMe extends Component {
render() {
return (
<div className='contact-body'>
<div className='contact-right'>
<div className='contact-side'>
<h2 style={{ fontSize: '25px', fontFamily: 'Anton', paddingTop: '10px'}}>
Contact Me
</h2>
<hr />
<div className='contact-list'>
<div className='form'>
<form action="contact.php" method='post'>
<input type="text" name="name" placeholder="Your name..." />
<input type="email" name="email" placeholder="Your email..." />
<textarea name="message" placeholder="Message me..."></textarea>
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default ContactMe;
contact.php
<?php
if (isset($_POST['submit'])) {
$userName = $_POST['name'];
$userEmail = $_POST['email'];
$userMessage = $_POST['message'];
$emailSubject = 'New Message From My Website Visitor';
$emailBody = 'Visitor Name: ' . $userName . '\n\n' .
'Visitor Email: ' . $userEmail . '\n\n' .
'Message: ' . $userMessage . '\n\n';
$emailTo = 'james_ross#outlook.fr';
$headers = 'From: ' . $emailFrom . '\n\n';
mail($emailTo, $emailSubject, $emailBody, $headers);
header('Location: index.js/mailsent');
}
If I need to use another technique/language in place of the PHP, please advise me of s decent source to read up on it, Thank you,
action="contact.php" is a relative link and it looks like your frontend runs as xxx/index.js/, you have to set it to an absolute url like action="/contact.php" or action="xxx/contact.php" where xxx is the folder with your php script.
If you develop with react than you don't want to switch between server side and client side pages, just send your form with ajax and display the output in your react app.
Your PHP code has a security issue:
$emailFrom is not defined, if you have some old PHP configuration with register_globals than it is possible to insert own header content and f.e. send spam emails to any email addresses.

Can't get rid of blank php page after submission form

Were searching for few hours answer on this but I'm completely stacked and brain freezes.
Have subscribe php form with bootstrap modal on successful submission. Everything works, emails passing through, modal showing just after one second or less blank page appear.
I guess that is loaded before form.php file is a separate file but is it there a way to stop loading blank page?
Here is Html code
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Send</button>
</div>
</form>
<!-- Sart Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="modal-title">Thank you</h4>
</div>
<div class="modal-body">
<p>Thank you for registering, we have added you to the waiting list!
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
And here is php code
<?php
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
window.stop();
});
</script>";
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
Also want to change Error messages to show up over modals also, that have it generated just not sure if can call two modals from same index file?
Any help is highly welcome!
Thanks, K>
What you are trying to achieve seems different from what you actually coded.
Let's look at your HTML form. You have attached Bootstrap's data-toggle and data-target attributes on your submit button. This means that when you click that button, it will open the modal AND submit the form. So the user will briefly see a modal and see the page redirect to your PHP file. (This is why you are seeing a modal appear briefly.)
Next, let's look at your PHP file. First of all, when you submit a form from one page to another page, that latter page has no idea of the HTML elements in your former page. This means the code you have inside your echo'd <script> tag actually should not be working as it is looking for an HTML element on your former page.
Now, for your question as to why are you getting a blank page? Well... everything is working fine so your code echo's a <script> tag -- which has no visual indicator. But like I just said, what you have inside the <script> does not work -- so nothing shows up and nothing happens.
So recap of the order of events when you click your button: the modal shows up, the form submits, the form redirects to another page, and that other page echo's nothing.
Below is a poor/quick solution to what I think you are trying to achieve:
Change your HTML file to a PHP file.
Remove data-toggle and data-target attributes off your button, so that it doesn't open the modal right when you click the button
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
Move your echo'd script tag from your PHP submission page to your PHP form page and wrap it in a condition as shown below:
<?php if (!empty($_GET['success'])) : ?>
<script>
$(document).ready(function(){
$("#myModal").modal();
});
</script>
<?php endif ?>
Remove your echo'd script tag lines of code in your PHP submission page. Instead, add a code so that it redirects back to your PHP form page. The key part is that you will append a ?success=true at the end of your URL.
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // valid email or null|false
if ($email) {
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $email;
if (mail($to, $subject, $body, $headers, "-f " . $from)) {
header('Location: subscribe.php?success=true'); // replace `subscribe.php` with PHP form page
exit;
}
echo 'There was a problem with your e-mail (' . $email . ')';
} else {
echo 'There was a problem with your e-mail'; // no point in printing $email if it is null
}
Basically, passing ?success=true is for telling the PHP form page that everything went well to open the modal (3).
And that should be it.
A better approach is to learn and use AJAX.

PHP mail script auto-runs same time every night

I'm having an issue where my PHP mail code runs every night at like 11:30pm. I'm sure no one is clicking the form submission button. The email contents are empty.
In my PHP mail code, I add the contents to a database just in case the email does not go through, then send the email as well.
Thanks
Form:
<form action="background/mail.php" method="POST">
<div class="row">
<div class="six columns">
<label>Your email</label>
<input class="u-full-width" type="email" placeholder="example#validmail.com" name="email">
</div>
<div class="six columns">
<label>Reason for contacting</label>
<select class="u-full-width" name="reason">
<option>Inquiry</option>
<option>Order</option>
<option>Other</option>
</select>
</div>
</div>
<div class="row">
<div class="u-full-width">
<label>Message</label>
<textarea class="u-full-width" placeholder="Enter message here" name="message"></textarea>
<input class="button-primary" type="submit" value="Submit">
</div>
</div>
</form>
mail.php:
<?php
$to = "support#website.ca";
$reason = "CUSTOMER MAIL: " . $_POST['reason'];
$email = $_post['email'];
$msg = $_POST['message'] . "\nemail: " . $email;
$header = "MIME-Version: 1.0\r\n";
$header.= "Content-type: text/html\r\n";
$header.= "From: " . $email . "\r\n";
$header.= "Reply-to: support#website.ca\r\n" . "X-Mailer: PHP/" . phpversion();
require("login.php");
$sql = "INSERT INTO emails (email, message, reason) VALUES ('$email','$msg','$reason')";
if($conn->query($sql) === TRUE){
mail($to,$reason,$msg, $header);
echo "Added to database, mail sent.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Most likely someone is making POST requests directly to your mail script to send out emails. There are some non-fool-proof ways to stop this:
Add some checking for the contents of the POST request. e.g. no empty body, valid email address, other logical checking. (you should be doing this anyway).
Add an additional hidden field to your form that is empty. Confirm that it is empty in mail.php in order to proceed. The idea: crawlers try to fill all form fields, but a user won't fill in a hidden form field
Add a hidden field and fill it with some value using JS and validate in mail.php. Crawlers cant use Javascript so the field will be empty (gotcha: will not work for users that disable JS).
Any of these can be circumvented, but they are trivial to implement and make things slightly more difficult for the crawler.
For true security there are more complex solutions. Maybe someone can outline those in an answer.
As I stated in comments in having fallen victim to a bot (or many bots); here is what I use to block out certain IP addresses and used as an include in every file.
You should also check for empty() fields and use an isset() against a submit button.
The following doesn't need the last 4th set, but you can always add to it, as it checks for anything following the 3rd set.
You can even narrow it down to using only 2 sets.
$ip = $_SERVER['REMOTE_ADDR'];
$nums = explode(".", $ip);
$if = "{$nums[0]}.{$nums[1]}.{$nums[2]}";
$blacklist = array(
"184.154.139",
"123.4.111",
"234.5.678"
);
if (in_array($if, $blacklist)) {
// echo "Rejected";
header("Location: http://www.example.com/");
exit;
}
else {
// Run your other code to do the variable check, mail processing etc.
}
I.e.:
Name your submit button:
<input name="submit" class="button-primary" type="submit" value="Submit">
Then check if it's set and that none of the POST arrays are (not) empty:
if(isset($_POST['submit'])){
if(!empty($_POST['reason']) && !empty($_POST['email'])){
$reason = $_POST['reason'];
$email = $_POST['email'];
// Run your executables in here
}
}
Another effective method is to use a checkbox and to validate if it was checked or not.
Also as stated, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Plus, that syntax error about $_post that I stated in comments, needs to be in uppercase $_POST as it's a superglobal.
http://php.net/manual/en/language.variables.superglobals.php

Sending an email using php

Given a standard html form such as the one below;
<form method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>>
<div class="row half">
<div class="6u"><input type="text" placeholder="Name" name="name" /></div>
<div class="6u"><input type="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="message" placeholder="Message" name="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" name="submit" /></li>
<li><input type="reset" class="button alt" value="Clear Form" name="clear"/></li>
</ul>
</div>
</div>
</form>
And the following php
if(isset($_POST['submit'])){
$to = "enquiries#appcloudkent.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Website Enquiry";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
if(isValidString($from) && isValidString($name) && isValidString($message)){
mail($to,$subject,$message,$headers);
}
}
It is possible to send an email, however, this approach causes a couple of problems. Because my form is at the bottom of the page, when send is clicked the page is redirected back and the focus goes back to the top of the page.
What is the correct way to provide adequate user feedback to let the user know the email was sent, is it possible to navigate back to the page and automatically scroll to the bottom - allowing me to change the send button to green or something?
Failing that, is there a better approach to doing this?
Thanks
Add an anchor link before your form.
<a id="anchorName"></a>
Post your form to the anchor.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#anchorName">
The form action should point to the page itself (like it does in your example) so you can display error messages from validation (like you don't).
If the form is not at the top of your page you can add an anchor:
<h2><a name="theForm">The form</a></h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#theForm">
If the form is processed properly (=mail sent), it is good practice to redirect to another page, showing a success message. So pressing F5 doesn't submit the form again (and send another mail).
if (mail($to,$subject,$message,$headers)) {
// redirect to page showing success message and exit script
} else {
// redirect to page showing error message and exit script
}
I usually redirect to the same page again, but attach an param ($_SERVER["PHP_SELF"].'?mail_success=1') and then inside the template I decide whether to show the success message, error message or the form:
if (isset($_REQUEST['mail_success'])) {
// show success message
} elseif (isset($_REQUEST['mail_error'])) {
// show error message, technical issues, try again bla bla
} else {
// show the form (including validation errors if necessary)
}
You could submit the form using an XMLHttpRequest, and cancel the default action of pressing submit. jQuery's .post() and event.preventDefault() methods are particularly good at that.

Form fires every time Website is Accessed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My website has a form that fires every time the website is accessed. It's still in testing phases so I get over 100 BLANK emails a day just from refreshing the page (and yes, all of the inputs are required). The tricky part is that I have a jquery script included. The script fires when you hit the submit button: it then refreshes the page and scrolls down (using a hashtag) to below my form with a message that basically says "thanks for emailing me!"
My code is posted below, but what I need to know is why I keep getting these blank emails even when the input fields are required! I am still very very new to php and jquery.
<?php
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
$sent = mail($to, $subject, $message) ;
if($sent) {
echo "";
}else{
echo "";
}
?>
<form data-abide name="input" action="index.php#hashtag" method="Post" id="theForm">
<div class="row">
<div class="small-10">
<div class="row">
<div class="small-12 columns name-field">
<input type="text" name="name" required id="right-label" placeholder="Name">
<small class="error">Name is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns email-field">
<input type="email" name="email" required id="right-label" placeholder="E-mail Address">
<small class="error">An email address is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="text" name="subject" required id="right-label" placeholder="Subject">
<small class="error">A subject is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<textarea name="message" placeholder="Your Message Here" rows="4" required></textarea>
<small class="error">A message is required.</small> </div>
</div>
</div>
</div>
<br/>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<br/>
<div class="success_message">
<h3>Thank you for your message!</h3>
<p>Your email has been sent successfully and I appreciate you getting in touch with me. I will be sending a reply soon.</p>
</div>
<script>
$(document).ready(function() {
if(window.location.hash == '#hashtag') {
$('.success_message').show();
$("html, body").animate({ scrollTop: $('#theForm').offset().top }, 1000);
}
});</script>
You never bothered fencing off your code to check if a form submission was actually performed, so the code will fire EVERY time the page is loaded. You'd want something at least like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form ...
}
They're required on the browser side, but you have no server-side validation. Older browsers that don't respect HTML5's required attribute, bots, etc. will happily submit all day long.
At its simplest, just check that there's data in each field:
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
if($subject && $name && $email && $text) {
$sent = mail($to, $subject, $message) ;
...
You'd want to do more validation (like making sure $email is a valid format) but this'll at least prevent blank ones. Of note: your form is vulnerable to header injection. Using a proper library like SwiftMailer will make coding email easier as well as protecting you from malicious spambots somewhat.
As Marc B notes, by including the mailing code on the same page as the form, you're firing it whenever someone accesses that page. Typically, your POST handling should be in a different file/route.

Categories