I have a contact page which made with the help of PHPMailer. The minimal code is as follows
<form class="form-horizontal" method="POST" action="Mail.php" name="contactForm">
...
</form>
This works perfectly fine, but whenever I try to open Mail.php explicitly on the webserver, the webserver sends blank
email every time. Here's a screenshot of email whenever I access Mail.php
Below is the minimal code from PHPMailer's Mail.php
$mail->Subject = $subject;
$mail->Body = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
$mail->AltBody = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else {
echo "Message has been sent....You're being redirected.....";
}
How can I restrict the user to explicitly access Mail.php?
So, as suggested by Jiri Hrazdil and Ahmad Mobaraki, using isset
should solve my problem, but I couldn't figure out how to implement that. So I came up with my own solution. I check, if the variables are empty in the first place, So this way if anyone directly tries to access the file it'll show a message the Fields are empty
, This is the way I did it.
require 'PHPMailer/PHPMailerAutoload.php';
$yourName = $_POST['yourName'];
$sender = $_POST['emailID'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = 'email@email.com';
header('Refresh: 5; URL=whatever.php');
if(empty($yourName) || empty($sender) || empty($subject) || empty($message) || empty($message))
{
echo "Fields are empty";
}
else
{
//Working Code of PHP Mailer
}
You could add a condition to check, whether the values from the form are filled:
if (isset($_POST['sender'])) {
// send mail
}
you should check if the request is POST
in your php file for example:
if(isset($_POST['from'])){
// send email
}
when you try to open Mailer.php
explicitly, your request is GET
.
UPDATE:
from
is not form! it is one of your form inputs! : <input name="from" type="text">
, you can use another field, like : name
or message
, when you try to open Mailer.php
explicitly , none of from
or to
or name
or subject
or .... are filled with $_POST
so there is no need to check all of them!
it is just enough to check for example to
or from
:
if(isset($_POST['to'])){
// send email
} else {
die("forbidden! you can not open this file explicitly!")
}