when check email address of yahoo domain it gives notice in php - 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();

Related

PHP mail() won't send when included in other PHP file with user input email

I am generating a page of information from a database. I need to send an email with the page content as a reminder. (example here takes input as message)
It takes in an email address and is supposed to send the details to that address.
<div class="container">
<?php
$name = $_GET['info'];
if(isset($name)){
$info = explode('|', $name);
/*****************************************************
open conection to the mySQL database
******************************************************/
....
/*****************************************************
Populate the page
******************************************************/
$sql="Select information from table";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$content = $row['post_title'];
/*Reminder*/
echo '<div data-role="collapsible">
<h1>Send a reminder</h1>';
include("includes/email_reminder.php");
echo'</div>';
}
/*****************************************************
Close connection
******************************************************/
mysqli_close($con);
} else {
echo'Nothing selected. Go back <br>
<img src="img/icon/Back.png" style="height: 3em" > ';
}
?>
</div>
That creates a form at the bottom of the page to take in the email that needs that needs a reminder.
This is email_reminder.php:
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: myaddress#mail.com\n");
echo "reminder has been sent";
}
}
}
?>
I have used that form in isolation (just opened email_reminder.php on its own) and it sent emails correctly from whichever email address I used. It just doesn't send when included in the other script.
include(emai_reminder.php); needs single quotes surrounding the file name (and email correctly spelled: include('email_reminder.php');
But, it looks like you need more help than just this. For example, there is no field FROM in your form, although you reference $_POST["from"]. You're running validation against that variable, which doesn't exist, which fails validation, which prevents the else if block from running, which prevents mail() from ever being called.
Several reasons why mailing to different user-defined addresses may not work:
1.) Check the result from the mail() call is TRUE, just to make sure the underlying sendmail (if you are on Linux) did not return an error.
2.) Add additional headers to prevent problems when delivering mails to foreign SMTP hosts, an example may be found on PHP doc for mail()
3.) In some cases (i.e. when using SMTP on Windows) using the PEAR Mail package may solve your problem. It also supports ASMTP and error trapping is much easier compared to the mail() function.

php subscription success text not working properly

Okay so basically i have this subscription input where people enter their email and click a button... Once they click the button the company email gets notified of the new subscriber (it receives a email and in the email states the email the user inputted)... anyways i've got it working so it does that and also writes whatever the user inputted into a .txt file.. Its all working but after i successfully got it to write to the text file, the success text after clicking the subscribe button dosent show...
HTML:
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="assets/sendmail.php" method="post">
<input type="text" name="email" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
PHP:
<?php
// Email address verification
function isEmail($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|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", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'subscriptions#servready.com';
$subscriber_email = ($_POST['email']);
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body, $headers);
}
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
?>
If i remove this part of the php script, the success and invalid email text pops up:
$data = $_POST['email']."\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
Like i said, its functional, but the success text or invalid email errors and success texts don't pop up with the code that writes the persons emails to the text file.
Site is http://servready.com for testing
Per the comments above, it is the content being echoed out after echo json_encode -- the extra content breaks the JSON echoed out causing everything else to break.
http://servready.com/assets/js/scripts.js is the JS file with your countdown time in it -- it's hardcoded into the script, so that's why it starts over. You'd need to put some code in there to determine the appropriate time for the countdown to reflect. I sugget you give that a try and then post a followup question with any issues you may need assistance with.
Glad to help!

E-mails not getting sent

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.

Form data store in CSV with IP: Undefined error

I am trying to get email, country and IP address from visitor and store into CSV and also will send email to the site owner.
I am not much familiar but I got most thing works but not able to rid off Undefined error for $cvsData .= "\"$email\",\"$ip\"".PHP_EOL; line...
Error Message: Notice: Undefined index: ip_address in
Here is my code
<?php
// this is to store form into csv file
if(isset($_POST["submit"]))
{
$email = $_POST["email"];
$ip = $_SERVER['REMOTE_ADDR'];
if(empty($email))
{
echo "ERROR MESSAGE";
die;
}
$cvsData .= "\"$email\",\"$ip\"".PHP_EOL;
$fp = fopen("emails.csv", "a");
if($fp)
{
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
echo "<h3>Thank you! we will inform you.....</h3>";
}
}
// this is to send email to site owner
// Contact subject
$email ="$email";
// Enter your email address
$to ='myemail#site.com';
$subject ='site Email Submited';
$send_email=mail($to,$email,$subject);
// Check, if message sent to your email
// display message "We've recived your information"
if($send_email){
echo "Email address is sent to the department.";
} else {
echo "ERROR";
}
?>
Form has only one field name="email" and submit button
Error is not in your code (that you pasted in) because ip_address is not mentioned.

System not acting as should (can't really be more specific)

I have a system where the user sends an email using a form (simple).
HTML form
<form method="post" action="process.php">
<label class="fieldLabel">Your email:</label><label class="errorLabel"><?php echo $form->error("email"); ?></label>
<input type="text" name="email" maxlength="100" class="email" value="<?php echo $form->value("email"); ?>" />
<label class="fieldLabel">Your enquiry:</label><label class="errorLabel"><?php echo $form->error("body"); ?></label>
<textarea name="body" class="enquiry"><?php echo $form->value("body"); ?></textarea>
<input type="submit" name="enquiry" class="button" value="Send Message"/>
</form>
On the same page, I have this if statement
if(isset($_SESSION['enq'])){
if($_SESSION['enq']){
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
Now the process.php file the form directs to
class Process{
//class constructor
function Process(){
if(isset($_POST['enquiry'])){
$this->enquiry();
}
}
function enquiry(){
global $session, $form;
//Registration attempt
$retval = $session->enquiry($_POST['email'], $_POST['body']);
//Successful
if($retval == 0){
$_SESSION['enq'] = true;
header("Location: contact-us.php");
}
//Error found with form
else if($retval == 1){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: contact-us.php");
}
//Failed
else if($retval == 2){
$_SESSION['enq'] = false;
header("Location: contact-us.php");
}
}
};
And now the session page where everything happens
//enquiry being made
function enquiry($email, $body){
global $form;
//check email entered
$field = "email";
if(!$email || strlen($email = trim($email)) == 0){
$form->setError($field, "* Not entered");
}
//check body(s) entered
$field = "body";
if(!$body || strlen($body = trim($body)) == 0){
$form->setError($field, "* Not entered");
}
//if errors exist, send them back to the user
if($form->num_errors > 0){
return 1; //errors with form
}
else if($form->num_errors == 0){
$this->customerEnquiry($email, $body);
return 0; //successful
}
else{
return 2; //failed
}
}
//send the enquiry to the account email
function customerEnquiry($email, $body){
$from = "From: ".$email." <".$email.">";
$to = "random#email.com";
$subject = "Website enquiry from ".$email."";
return mail($to,$subject,$body,$from);
}
Ok my problem is that the errors aren't coming back if I don't fill in the form. Also, the success text isn't being displayed if I don't?
Anyone see a problem with how this flows?
Hoping I have just missed something simple!
Thanks!
I noticed this bit of code.
if(isset($_SESSION['enq'])){ // <---This...
if($_SESSION['enq']){ // <---And This
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
If $_SESSION['enq'] is not set, then the IF statement inside that will never execute, meaning you will see neither the success nor failure message.
Also, are you starting the session anywhere on the page? If you never start a session, then $_SESSION['enq'] will never be set.
http://www.php.net/manual/en/function.session-start.php
This is a very strange way to go about this. For example you're displaying success/failure message before the e-mail has been sent.
Have you copy and pasted this?
The usual method to do this would be to have the logic in process.php only, this is where you'd do your validation (return message to user if failed) and ultimately send the e-mail.
In the long run I think you'd be better off modifying the flow as I'm currently having a hard time trying to follow it.

Categories