E-mails not getting sent - php

I have a contact form, but the messages are not sending to the email I have declared. This is the submit.php file:
<?php
/* config start */
$emailAddress = 'xxxxxxx#hotmail.com';
/* config end */
require "../php/class.phpmailer.php";
session_name("fancyform");
session_start();
foreach($_POST as $k => $v)
{
if(ini_get('magic_quotes_gpc'))
$_POST[$k] = stripslashes($_POST[$k]);
$_POST[$k] = htmlspecialchars(strip_tags($_POST[$k]));
}
$err = array();
if(!checkLen('name'))
$err[] = 'The name field is too short or empty!';
if(!checkLen('email'))
$err[] = 'The email field is too short or empty!';
elseif(!checkEmail($_POST['email']))
$err[] = 'Your email is not valid!';
if(!checkLen('subject'))
$err[] = 'You have not selected a subject!';
if(!checkLen('message'))
$err[] = 'The message field is too short or empty!';
if((int)$_POST['captcha'] != $_SESSION['expect'])
$err[] = 'The captcha code is wrong!';
if(count($err))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
$_SESSION['errStr'] = implode('<br />', $err);
$_SESSION['post'] = $_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
$msg =
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();
unset($_SESSION['post']);
if($_POST['ajax'])
{
echo '1';
}
else
{
$_SESSION['sent'] = 1;
if($_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
function checkLen($str, $len = 2)
{
return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]), "utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
If submit.php is opened in a browser, I get the following error message:
Warning: require(../php/class.phpmailer.php) [function.require]: failed to open stream:
No such file or directory in
/home/content/96/9227096/html/submit.php on line 10 Fatal error: require() [function.require]: Failed opening required
'../php/class.phpmailer.php'
(include_path='.:/usr/local/php5_3/lib/php') in
/home/content/96/9227096/html/submit.php on line 10
I was also told by my hosting server that I might need to add the following relay server in my code:(but I don't know where)
relay-hosting.secureserver.net

The statement require "../php/class.phpmailer.php"; means that the ../php/class.phpmailer.php file will be loaded and that if it can't be loaded then the script will terminate.
It is unable to load that script. That could be for any of a number of reasons. Maybe it's not there. Maybe the path you provided is wrong. Maybe it's a file permission issue. You'll have to figure that part out.
But since it can't load it, the script terminates with the error message.

I have encounter similiar problems on some hosting providers. Even if the path was good require did not include file and terminated whole script. You could write there a real path to your file, and maybe that will help. Since this problem I started to use
require(getcwd().'actual/path/relevant/to/index.php');
and starder to write apps in one class, similiar to Java or C# desktop apps.

Related

email domain validation in php on windows

I am asking for an email address through a form in my website. I want to validate the domain so that I can prevent fake entries I am getting right now. I am using the following code, but it dose not seem to work :
function myCheckDNSRR($hostName, $recType = '')
{
if(!empty($hostName)) {
if( $recType == '' ) $recType = "MX";
exec("nslookup -type=$recType $hostName", $result);
// check each line to find the one that starts with the host
// name. If it exists then the function succeeded.
foreach ($result as $line) {
if(eregi("^$hostName",$line)) {
echo "valid email";
}
}
// otherwise there was no mail handler for the domain
echo "invalid email";
}
echo "invalid EMAIL";
}
I am new to this and used this code from here
Please guide me. Thanks.
I guess you can simply ping like this.
function myCheckDNSRR($email_address)
{
if(!empty($email_address)) {
$hostName=strstr($email_address, '#');
$hostName=str_replace("#","www.",$hostName);
exec("ping " . $hostName, $output, $result);
if ($result == 0){
echo "valid email";
}
else{
echo "invalid email";
}
}
}
call it like
echo myCheckDNSRR("sample#gmail.com");
Use a validation lib like https://docs.zendframework.com/zend-validator/validators/email-address/
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
Create a table in your DB for storing an email link code. When someone registers, mark the user as unactivated until he clicks the link in the email. This way, you know it's real, and can activate the user.

when check email address of yahoo domain it gives notice in php

Hi i have used the php script for email validations.The code is working if i check the email address of gmail domain it gives correct result and check email is valid or invalid email. but when i check the email address of yahoo domain it gives error Notice: fwrite(): send of 6 bytes failed with errno=10053 An established connection was aborted by the software in your host machine.I want to avoid thie notice for yahoo address.
<div class="container" style="width:80%;margin:0 auto;">
<h3>Email Validation Script</h3>
<div class="form-group" >
<form method="post">
<label for="comment">Email Address</label>
<textarea class="form-control" name="em" id="" cols="30" rows="10" placeholder="please enter email addresses"></textarea >
<br>
<input type="submit" name="submit" value="Check email addresses" class="btn btn-primary">
</form>
</div>
</div>
require_once('smtp_validateEmail.class.php');
if(isset($_POST['submit'])){
$em= $_POST['em'];
$emails2=substr(strrchr($em, "#"), 1);
//echo $emails2;
// if($emails2 == 'yahoo.com'){
// echo "not valid";
// }
// else{
// echo "valid";
// }
$emails1 = implode(",", preg_split("/[\s]+/", $em));
$emails = explode(',',$emails1);
//$emails = array('dave1#hmgamerica.com', 'babita#gmail.com');
// an optional sender
$sender = 'user#yourdomain.com';
// instantiate the class
$SMTP_Validator = new SMTP_validateEmail();
// turn on debugging if you want to view the SMTP transaction
$SMTP_Validator->debug = true;
// do the validation
$results = $SMTP_Validator->validate($emails, $sender);
echo "<div class='container' style='width:77%;margin:0 auto;background:#F0F0F0;'>";
echo "<h3>List Of Emails</h3>";
// view results
foreach($results as $email=>$result) {
if ($result) {
echo "<div style='color:green';>
The email address $email is valid
</div>";
echo "<br>";
//mail($email, 'Confirm Email', 'Please reply to this email to confirm', 'From:'.$sender."\r\n"); // send email
} else {
// echo "not valid";
echo "<div style='color:red';>
The email address $email is invalid
</div>";
echo "<br>";
}
}
echo "</div>";
}
?>
The error is line fwrite($this->sock, $msg."\r\n");-
function send($msg) {
fwrite($this->sock, $msg."\r\n");
$reply = fread($this->sock, 2082);
$this->debug(">>>\n$msg\n");
$this->debug("<<<\n$reply");
return $reply;
}
Did you look up your error code (errno 10053)?
It hints that you are on Windows and the socket is aborting.
Perhaps: An established connection was aborted by the software in your host machine Windows 8.1
Did you try validating just one yahoo address with your library?
<?php
$SMTP_Validator = new SMTP_validateEmail();
$SMTP_Validator->debug = true;
$results = $SMTP_Validator->validate(array('foo#yahoo.com'));
var_dump($results);
You could be having some socket problems. The lib code suggests that upon socket creation failure the domain will be skipped. So it's as if the socket gets created but later there is a problem.
Try the following code in a separate file to see if you get any errors while connecting to a yahoo SMTP server:
<?php
if(getmxrr('yahoo.com', $mxhosts)) {
$sock = fsockopen ($mxhosts[0], 25, $errno , $errstr);
if(! $sock) {
var_dump($errno);
var_dump($errstr);
} else {
echo 'Socket created.';
}
}
You could also replace the lib's fwrite line temporarily (and test for just one yahoo address). This may indicate a time-out.
$meta = stream_get_meta_data($this->sock);
var_dump($meta);
die();

PHP Form not sending an email

I have a pre-made form built out of html/css/jquery/ajax. It is pretty much copy and pasted for the time being on my contact page.
This is what i call before my html tag on the contact.php page.
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<h1>Success! We will be in contact!</h1>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
http://jsfiddle.net/6B2G7/
Here is a jsFiddle for the css/html/jquery. The page loads fine, you can fill in the fields and click submit. It successfully submits, but i receive no email. Spell checked the necessary items, but to no avail, no emails.
Any help is greatly appreciated. Sorry if i left anything out -- new here. Tried using firebug to see if there was an error, but i'm not getting any.
==EDIT==
This is my submit.php, which now i'm wondering where does this need to be? I don't think it's actually calling it anywhere on my site which would explain why no email is being sent. Now i'm a little confused -- first day with PHP. How do i get it to submit to the email address given in the code?
<?php
/* config start */
$emailAddress = 'coreymaret#hotmail.com';
/* config end */
require "phpmailer/class.phpmailer.php";
session_name("fancyform");
session_start();
foreach($_POST as $k=>$v)
{
if(ini_get('magic_quotes_gpc'))
$_POST[$k]=stripslashes($_POST[$k]);
$_POST[$k]=htmlspecialchars(strip_tags($_POST[$k]));
}
$err = array();
if(!checkLen('name'))
$err[]='The name field is too short or empty!';
if(!checkLen('email'))
$err[]='The email field is too short or empty!';
else if(!checkEmail($_POST['email']))
$err[]='Your email is not valid!';
if(!checkLen('subject'))
$err[]='You have not selected a subject!';
if(!checkLen('message'))
$err[]='The message field is too short or empty!';
if((int)$_POST['captcha'] != $_SESSION['expect'])
$err[]='The captcha code is wrong!';
if(count($err))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
$_SESSION['errStr'] = implode('<br />',$err);
$_SESSION['post']=$_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
$msg=
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();
unset($_SESSION['post']);
if($_POST['ajax'])
{
echo '1';
}
else
{
$_SESSION['sent']=1;
if($_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
function checkLen($str,$len=2)
{
return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]),"utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
Can you just run submit.php on your browser? Or check spam of your email and try with other email address..
http://tutorialzine.com/2009/09/fancy-contact-form/
You might also want to consider the Mandrill API for email. It's really simple to set up:
var m = new mandrill.Mandrill('your_api_key');
function sendTheMail(){
m.messages.send({
"message": {
"from_email": document.getElementById('from_email').value,
"from_name": document.getElementById('from_name').value,
"to":[{"email": "your_email", "name": "your_name"}],
"subject": "optional_value",
"text": document.getElementById('message').value
}
});
}
And you could then set up your contact page like this:
<p>Your Name: <input type="text" id="from_name"></p>
<p>Your Email: <input type="email" id="from_email"></p>
Message<br><br><textarea rows=15 cols=50 id="message"></textarea><br>
<button onclick="sendTheMail();">Send</button>

Simple check of email address in Constant Contact

I can't find a damned bit of documentation for using the Constant Contact REST API to check if an email address is in a list or not.
The following seems to be completely useless:
include_once('cc_class.php');
$ccContactOBJ = new CC_Contact("basic", $cckey, $ccuser, $ccpass);
if(($_SERVER['REQUEST_METHOD']=="POST") && !empty($_REQUEST['member-submit'])) {
$contact = $ccContactOBJ->getSubscribers(urlencode($_POST['MemberEmail']));
if (empty($contact['items'])) {
$message = 'You are not listed in our database.';
}
else {
$message = 'You are already listed in our database';
}
echo $message;
}
Anyone have ANY idea how to return a true or false value?

How To solve dis synchronize of form Validation?

I am wondering if anyone out there can help with my form Validation Please?
I am having a few problems trying to synchronized out how certain bits of the actual structure of the script works together.
<?php
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])){
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
}
else{
$msg=$msg."Your Key is valid!<BR>";
$flag="OK";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
$flag="OK";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
}else{ // all entries are correct and let us proceed with the database checking etc …
}
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
}
?>
the problem, when email valid, password valid, though key is invalid the warning of key disappear, it mean passed too... and also the spamcheck doesn't look work..
You don't have to set the flag to 'OK' or a previous error get masked, as you already noted.
If all the check are ok, the flag remains in valid state and you can pass on, otherwise, if one of the check fails the flag reports the incorrect state.
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
} else {
$msg=$msg."Your Key is valid!<BR>";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Said that I would use a different approach, for example using boolean values other than a string named flag. You can obtain a more fluent code calling it something like $inputIsvalid.
Other nags: Sometimes you add the messages to a $msg variable, other you issue an echo, maybe it is an oversight.
There is a lot of room for improvements, as every other code, I will address just some of the easy issues, for examples I will not check if the variables are set or not.
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
} else {
$messages[]'Your Key is valid!';
}
}
$email=$_POST['email'];
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
$emailIsValid = eregi($emailRegEx, $email);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=$_POST['password'];
if(strlen($password) < 5 ){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Another approach should be (the functions are quite simple, but you can modify the validation policy of the different components without affecting the main code):
function validateKey() {
if(!isset($_POST['Send'])) {
return true;
}
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
return $key==$num_key;
}
function validateEmail($email) {
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
return eregi($emailRegEx, $email);
}
function validatePassword($password) {
return strlen($password) < 5;
}
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(validateKey()) {
$messages[]'Your Key is valid!';
} else {
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
}
$emailIsValid = validateEmail($_POST['email']);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=;
if(!validatePassword($_POST['password']){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Spam function:
why are you using Constant different than the boolena values?
(TRUE is different from true and FALSE is different from false)
You can rewrite the function like this in order to obtain the desired behaviour.
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
return filter_var($field, FILTER_VALIDATE_EMAIL);
}
if (isset($_POST['email'])) {//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if (!$mailcheck) {
echo "Invalid input";
}
}
Each of you tests sets flag to "OK" or "NOTOK" overwriting decisions made by previous tests.
You could start with $flag = true;. And only if a test decides that the input is unsatisfying it sets $flag=false.
Or you can remove $flag altogether and check if 0===strlen($msg) after the tests.

Categories