how to send an HTML content via php mail() - apache

I am trying to send an HTML e-mail using this code but all i am getting is FALSE from the mail() function.
The error_log is empty.
Can someone tell me why mail() is not working?
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>SDFSDF</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>VXCVSDF</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$to = 'my_mail#gmail.com';
$subject = 'Website Change Reqest';
$headers = "From: USER NAME"."\r\n";
$headers .= "Reply-To: USER EMAIL"."\r\n";
$headers .= "MIME-Version: 1.0"."\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.';
} else {
echo 'There was a problem sending the email.';
}

It's hard to debug PHP mail() function.
After checking your script, I can confirm that your code is working fine. It's something with your server or/and PHP configuration.
Start with this little snippet to see what is happening:
error_reporting(E_ALL);
ini_set('display_errors', -1);
echo '<br>I am : ' . `whoami`.'<br>';
$result = mail('myaddress#mydomain.com','This is the test','This is a test.');
echo '<hr>Result was: ' . ( $result === FALSE ? 'FALSE' : 'TRUE') . ' ('. $result. ')';
echo '<hr>';
echo phpinfo();
After output, check your sendmail_path, in most case sendmail_path uses sendmail MTA:
/usr/sbin/sendmail -t -i
Edit your php.ini file, set the following and don't forget to restart httpd server:
sendmail_path = /usr/sbin/sendmail -t -i
Check log files at /var/log/maillog, it could really help you to solve the problem.
If you still have a problem, just take a good look at PHPMailer, SwiftMailer, PEAR's Mail or Zend Framework's Zend_Mail an excellent, comprehensive, modern PHP mailing library. It will be easy to debug your problem after all.

You can using phpmailer for this way!
https://code.google.com/a/apache-extras.org/p/phpmailer/
Hope this help!

Related

Using ini_set in PHP file

I just asked this question here regarding sending email from Windows server. Got the answer that the php.ini file has to be configured. After reading a little bit more, I found out about ini_set() function in PHP. So I tried to use it like that:
ini_set('SMTP', 'mail.mysite.com');
ini_set('smtp_port', 25);
ini_set('auth_username', 'me#mysite.com');
ini_set('auth_password', 'mypass');
ini_set('sendmail_from', 'me#mysite.com');
function send_contact_form($strName, $strEmail, $strPhone, $strMessage)
{
$to = 'mymail#mysite.com';
$subject = 'From the site';
$message = '<html lang="HE">
<head>
<title>
'.$subject.'
</title>
</head>
<body style="text-align:right; direction:rtl; font-family: Arial;">
Name: '.$strName.'<br>Email: '
.$strEmail.'<br>Phone: '.$strPhone
.'<br><br>Message: <br>'.$strMessage.'
</body>
</html>';
$email = $strEmail;
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$header .= "From: $email\r\nReply-To: $email" . "\r\n";
mail($to, $subject, $message, $header);
}
However, I still don't receive any email. What am I doing wrong? Why is it not working?

Apple Push notification script not working

I am using this php script but its producing output Message successfully delivered but not sending notification. i have already check device id and certificates they are perfect and working fine with another script.
<?php
// Put your device token here (without spaces):
$deviceToken = 'fbf04bf4ace2f1e823016082da3a798cf3ab666ae99a395b65e364eb4c6d6d4a';
// Put your private key's passphrase here:
$passphrase = '123';
// Put your alert message here:
$message = 'A push notification has been sent!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'key.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array('alert' => array('body' => $message, 'action-loc-key' => 'Look', ), 'badge' => 2, 'sound' => 'oven.caf', );
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
echo "<pre>Result : ";
print_r($result);
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
Can any one help me to getting out of this.?
Thanks in advance
I encounter similar problem when i first start iOS push notifications
There Will be possibility that you are doing a development push rather than a production push
Change the server to ssl://gateway.sandbox.push.apple.com:2195 and use your development push notification key to give a try.
That solves my problem
I think you have to change port number
You code: ssl://gateway.push.apple.com:2195. 2195 use for sandbox and 2196 use for live.
Can you please change it and try.
Hope this work.

PayPal IPN Updates to Accommodate HTTP1.1 - Connection reset by peer

We have been working to update our PayPal IPN scripts in accord with seom recent changes. Here is the instruction in part by PayPal ...
Your Action Required before February 1, 2013 You will need to update
your IPN and/or PDT scripts to use HTTP 1.1, and include the "Host:
www.paypal.com" and "Connection: close" HTTP headers in the IPN and
PDT scripts.
We did that and the IPNs failed. PayPal Merchant Technical Service asked that we move to a SLL connection. Previously our connection to PayPal had been based upon ...
fsockopen ('www.paypal.com', 80, $errno, $errstr, 30)
Now it is ...
fsockopen ('ssl://ipnpb.paypal.com', 443, $errno, $errstr, 30)
We had to overcome an SSL problem with our host config to get this working, but it now makes the connection. However IPN requires us to post back to PayPal in order to receive a "VERIFIED" notification, at which point the script can do it's local processing based upon a confirmed payment.
This is where it fails.
The lines of the sample PayPal script are:
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp (trim($res), "VERIFIED") == 0) { ... rest of script
But the response comes back blank. I have inserted a diagnostic to email me the value of $res at each stage. If I do this with the old script it comes back with a "VERIFIED" value just fine. The old scripts on several sites have been stable for years. I have now tried these new updates on two distinct sites on two different servers and the result is the same.
When looking at the Apache logs I see this error:
PHP Warning: fgets() [function.fgets]: SSL: Connection reset by peer in /home/[sitename]/public_html/[IPN scriptname].php on line 145
So it appears that PayPal shuts down the connection without sending a Verified response. However PayPal support deny that this is a problem at this end since the connection is opening in the first place.
I have spent several days trying to fix this. I still have the deadline of Feb 1st after which PayPal say my old scripts may not work, but neither do the new ones.
Anyone else have any experience with this?
If anyone else has the same issue, CURL seems to be the recommend choice for IPN by PayPal.
Check out there code sample on Github at: https://github.com/paypal/ipn-code-samples/blob/master/paypal_ipn.php
After struggle this issue a few hours. I got it right.
first, the header should be correct.
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.sanbox.paypal.com\r\n";
$header .= "Accept: */*\r\n";
$header .= "Connection: Close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "\r\n";
second, the buffer should be big enough to receive whole msg from Paypal. the original sample code use 1024, but the result got truncated.
$res = stream_get_contents($fp, 2048);
After the two, the result return good.
Finaly found an answer! Paypal IPN Script, issue with feof and fgets
remove while(!feof($fp) ... and change it to $res = stream_get_contents($fp, 1024); also add $header .= "Conection: Close" to make sure that paypal closes the connection.
UPDATE: Jan 7th 2016
I noticed that the below works very well for tls://www.sandbox.paypal.com but when you go live to tls://www.paypal.com connection is refused! (It doesn't work) I found the problem is in the headers, sandbox and production level live paypal needs different headers! This is a bug but for you to get it work both in production level and sandbox, please use these headers respectively:
Production Level (Live PayPal Headers):
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
Sandbox PayPal Headers:
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Accept: */*\r\n";
$header .= "Connection: Close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "\r\n";
* The code below is the same and it works fine, just replace the headers respectively.*
Here is the rest of the code (and answer):
I checked all of the answers here and there to make it work in Jan 5th 2016.
All of them had good points, but didn't work for the whole picture.
So first, here is the complete code that actually works and then I'll go through it:
<?php
// =========================================================================
// PayPal Official PHP Codes and Tutorial:
// https://developer.paypal.com/webapps/developer/docs/classic/ipn/gs_IPN/
// =========================================================================
// Send an empty HTTP 200 OK response to acknowledge receipt of the notification
header('HTTP/1.1 200 OK');
// Assign payment notification values to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
// Build the required acknowledgement message out of the notification just received
$req = 'cmd=_notify-validate'; // Add 'cmd=_notify-validate' to beginning of the acknowledgement
foreach ($_POST as $key => $value) {
// Loop through the notification NV pairs
$value = urlencode(stripslashes($value)); // Encode these values
$req .= "&$key=$value"; // Add the NV pairs to the acknowledgement
}
// Set up the acknowledgement request headers
// HTTP POST request
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.sanbox.paypal.com\r\n";
$header .= "Accept: */*\r\n";
$header .= "Connection: Close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "\r\n";
// Open a socket for the acknowledgement request
$fp = fsockopen('tls://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
// Send the HTTP POST request back to PayPal for validation
fputs($fp, $header . $req);
// Log the transaction:
file_put_contents("paypal_post.txt", date('Y-m-d H:i:s')."\n".file_get_contents("php://input")."\n\n", FILE_APPEND);
// While not EOF
while (!feof($fp)) {
// Get the acknowledgement response
// $res = fgets($fp, 1024);
$res = stream_get_contents($fp, 1024);
$responses = explode("\r\n", $res);
foreach ($responses as $response) {
if (strcmp ($response, "VERIFIED") == 0) {
// Response contains VERIFIED - process notification
// Authentication protocol is complete - OK to process notification contents
// Possible processing steps for a payment include the following:
// Check that the payment_status is Completed
// Check that txn_id has not been previously processed
// Check that receiver_email is your Primary PayPal email
// Check that payment_amount/payment_currency are correct
// Process payment
} else if (strcmp ($response, "INVALID") == 0) {
// Response contains INVALID - reject notification
// Authentication protocol is complete - begin error handling
}
}
}
// Close the file
fclose($fp);
?>
OK, now you have the code that works to listen for a PayPal IPN, re-compile and send it back to PayPal for verification, receive the headers back, process the headers line by line to find the VERIFIED validation.
Which should be provided by PayPal all-in-one package in a working condition but their tutorial lacked very critical parts and it didn't work for me and many here on this thread.
So now what are the critical parts that makes it work:
First, the headers provided by paypal didn't work, I found #jp_eagle 's headers work perfectly.
And paypal was wrong for $res = fgets($fp, 1024); as well...
However you dont need $res = stream_get_contents($fp, 2048); as #jp_eagle suggested, $res = stream_get_contents($fp, 1024); is just fine.
while (!feof($fp)) {} loop should stay there to make it work! Yes, even with the switch from fgets() to stream_get_contents() it should stay there!
#richbai90 was wrong for the suggestion to remove it.
Try the other way and it won't work...
And the most critical part to get the VALIDATION is this loop:
$res = stream_get_contents($fp, 1024);
$responses = explode("\r\n", $res);
foreach ($responses as $response) {}
Now you can look for the VALIDATION in each line here:
if (strcmp ($response, "VERIFIED") == 0) {}
Also logged the initial complete incoming POST request form paypal before anything else:
// Log the transaction:
file_put_contents("paypal_post.txt", date('Y-m-d H:i:s')."\n".file_get_contents("php://input")."\n\n", FILE_APPEND);
That's it.
Now go here and login with your paypal to see if it works:
https://developer.paypal.com/developer/ipnSimulator/
Give your url select "cart checkout" for example and send a test IPN.
If it works all good, go ahead and remove the .sandbox from the above paypal URL from www.sandbox.paypal.com to www.paypal.com and you are live.
Fill in the VERIFIED and INVALID sections in the if-else statements with your database actions and it is done.

PHP mail out late or when Apache server rebooted

I used to have php mail out right away, now however it might be changes in php code on page, or fact that i changed servers. Mail out like 10 minutes after user register, but if i go and restart apache it goes trough right after apache restart.
What settings should i tweak for php or apache to make it send right away again.
P.S. this is random issue sometimes it sends right away!
$from = "mail#otherdomain.com";
$email_address = $ex[0][Email_Address];
$ttc = "mymail#domain.com";
$eol = "\r\n";
$mime_boundary = md5(time());
$headers .= "From:".$from .$eol;
$headers .= "Reply-To:".$from.$eol;
$headers .= "Return-Path:".$from.$eol;
$headers .= "Bcc:".$ttc.$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: text/html; charset=iso-8859-1".$eol;
if (preg_match("/gmail/",$to))
$headers = str_replace("\r\n","\n",$headers);
$result=mail($email_address,$subject,$mess,$headers);
header("location:home.html");

Joomla User login check

First I am not a joomla developer. My friend has a web site created with joomla 1.5. In webroot there are some joomla files. I created a directory in webroot "mydirectory" and i have an index file in this directory. I try to access joomla's user info in this page i grab the user object but it doesn't work.
//i included joomla core files
$user =& JFactory::getUser();
if ($user->get('guest')) {
echo 'guest';
} else {
echo 'not guest';
}
when I log in to my account, it says 'guest' again.
Also, I can't find anything in Joomla's session class.
$session =& JFactory::getSession();
Thanks
You should do this:
$user =& JFactory::getUser();
if (!$user->guest) {
echo 'You are logged in as:<br />';
echo 'User name: ' . $user->username . '<br />';
echo 'Real name: ' . $user->name . '<br />';
echo 'User ID : ' . $user->id . '<br />';
}
This is from here: http://docs.joomla.org/JFactory/getUser
Try print_r($user) to see what items you are getting back.
Try to check for $user->id
See if you are missing including any file e.g. framework.php