I have a mail application that send about 5000 emails daily(a lot of account paperwork) via cron job, and works fine when the mail is sending to just one recipient. The problem comes when we activate the BCC copy, then the app starts sending until 980-1050 mails and start recieving 4.5.3 error from the smtp(Too many recipients). If i pause the job and run the cron again, the php process got a new pid, and start sending ok until it reach the same limit(980-1050 mails);
So my question is: is there a way to regenerate the php process id ?
If i was capable to do that, then the app would send those mails without problem.
Or maybe i'm missing some postfix configuration?
Relevant part of the code:
/**
* _Send_SmtpData
* Handles the SMTP negotiation for sending the email header and body.
*
* #param String $rcpt_to The 'receipt to' address to send the email to. This is a bare email address only.
* #param String $to The 'to' address to send this to. This can contain a name / email address in the standard format ("Name" <email#address>)
* #param String $subject The subject of the email to send.
* #param String $body The body of the email to send.
* #param String $headers The headers of the email to send.
**/
function _Send_SmtpData(&$rcpt_to, &$to, &$subject, &$body, &$headers)
{
$data = "DATA";
$this->DebugMemUsage('Trying to put ' . $data);
if (!$this->_Put_Smtp_Connection($data)) {
$this->ErrorCode = 12;
$this->ErrorCodeSMTPEnhanced = false;
$this->Error = GetLang('UnableToSendEmail_Data');
$this->_Close_Smtp_Connection();
$this->DebugMemUsage('Got error ' . $this->Error);
return array(false, $this->Error);
}
$response = $this->_get_response();
$this->DebugMemUsage('Got response ' . $response);
$responsecode = substr($response, 0, 3);
if ($responsecode != '354') {
$this->ErrorCode = $responsecode;
$this->ErrorCodeSMTPEnhanced = $this->_GetSMTPEnhancedErrorCode($response);
$this->Error = $response;
$this->_Close_Smtp_Connection();
$this->DebugMemUsage('Got error ' . $this->Error);
return array(false, $this->Error);
}
$msg = "To: " . $to . $this->_smtp_newline . "Subject: " . $subject . $this->_smtp_newline . $headers . $this->_smtp_newline . preg_replace('/^\.(\r|\n)/m', ' .${1}', $body);
$msg = str_replace("\r\n","\n",$msg);
$msg = str_replace("\r","\n",$msg);
$lines = explode("\n",$msg);
foreach ($lines as $no => $line) {
// we need to rtrim here so we don't get rid of tabs before the start of the line.
// the tab is extremely important for boundaries (eg sending multipart + attachment)
// so it needs to stay.
$data = rtrim($line);
$this->DebugMemUsage('Trying to put ' . $data);
if (!$this->_Put_Smtp_Connection($data)) {
$this->ErrorCode = 13;
$this->ErrorCodeSMTPEnhanced = false;
$this->Error = GetLang('UnableToSendEmail_DataWriting');
$this->_Close_Smtp_Connection();
$this->DebugMemUsage('Got error ' . $this->Error);
return array(false, $this->Error);
}
}
$data = $this->_smtp_newline . ".";
$this->DebugMemUsage('Trying to put ' . $data);
if (!$this->_Put_Smtp_Connection($data)) {
$this->ErrorCode = 14;
$this->ErrorCodeSMTPEnhanced = false;
$this->Error = GetLang('UnableToSendEmail_DataFinished');
$this->_Close_Smtp_Connection();
$this->DebugMemUsage('Got error ' . $this->Error);
return array(false, $this->Error);
}
$response = $this->_get_response();
$this->DebugMemUsage('Got response ' . $response);
$responsecode = substr($response, 0, 3);
if ($responsecode != '250') {
$this->ErrorCodeSMTPEnhanced = $this->_GetSMTPEnhancedErrorCode($response);
$this->ErrorCode = $responsecode;
$this->Error = $response;
$this->_Close_Smtp_Connection();
$this->DebugMemUsage('Got error ' . $this->Error);
return array(false, $this->Error);
}
$this->DebugMemUsage('Mail accepted ');
/**
* We got this far, this means we didn't encounter any errors.
* Cleanup previous error codes and variables since they are no longer relevant
* with the current process iteration.
*/
$this->Error = '';
$this->ErrorCode = false;
$this->ErrorCodeSMTPEnhanced = false;
$this->_smtp_email_count++;
return array(true, false);
}
In the end the "bug" was in another function, the bcc copy function; in every call for the working process, it was not cleaning the previous bcc copies of the mail, but sum them until they reach the limit.
Related
Friends, please explain to me why PHPMailer does not send an email?
He must send a letter after payment. The usual mail() function works, but with PHPMailer I already broke my head. HELP
After payment, this file receives a notification from Yandex that the payment has been made. I made a condition that if the payment is made, then a corresponding letter is sent to the mail.
works, despite the mistake
Fatal error: Uncaught TypeError: Argument 1 passed to YandexCheckout\Model\Notification\NotificationWaitingForCapture::__construct() must be of the type array, null given, called in /home/birdyxru/public_html/test/requests.php on line 25 and defined in /home/birdyxru/public_html/test/assets/lib/Model/Notification/NotificationWaitingForCapture.php:72 Stack trace: #0 /home/birdyxru/public_html/test/requests.php(25): YandexCheckout\Model\Notification\NotificationWaitingForCapture->__construct(NULL) #1 {main} thrown in /home/birdyxru/public_html/test/assets/lib/Model/Notification/NotificationWaitingForCapture.php on line 72
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
require 'assets/lib/autoload.php';
require 'db/connect.php';
// Получите данные из POST-запроса от Яндекс.Кассы
$source = file_get_contents('php://input');
$requestBody = json_decode($source, true);
// Создайте объект класса уведомлений в зависимости от события
// NotificationSucceeded, NotificationWaitingForCapture,
// NotificationCanceled, NotificationRefundSucceeded
use YandexCheckout\Model\Notification\NotificationSucceeded;
use YandexCheckout\Model\Notification\NotificationWaitingForCapture;
use YandexCheckout\Model\NotificationEventType;
use YandexCheckout\Model\PaymentStatus;
try {
$notification = ($requestBody['event'] === NotificationEventType::PAYMENT_SUCCEEDED)
? new NotificationSucceeded($requestBody)
: new NotificationWaitingForCapture($requestBody);
} catch (Exception $e) {
// Обработка ошибок при неверных данных
}
// Получите объект платежа
$payment = $notification->getObject();
if($payment->getStatus() === PaymentStatus::SUCCEEDED) {
$payment_id = $payment->getId();
}
if(isset($payment_id)) {
$email = R::getCell("SELECT `email` FROM `logs` WHERE `payment_id` = '$payment_id'");
$date = R::getCell("SELECT `date` FROM `logs` WHERE `payment_id` = '$payment_id'");
$time = R::getCell("SELECT `time` FROM `logs` WHERE `payment_id` = '$payment_id'");
$report_name = strtok("$email", '#') . ' ' . $date . ' ' . $time;
// Отправка сообщения
$mailTo = $email; // Ваш e-mail
$subject = "На сайте совершен платеж"; // Тема сообщения
// Сообщение
$message = "Платеж на сумму: " . $report_name . "<br/>";
$message .= "Детали платежа: " . $payment->description . "<br/>";
$headers= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: info#site.ru <info#site.ru>\r\n";
mail($mailTo, $subject, $message, $headers);
}
?>
does not work :(
<?php
require 'assets/lib/autoload.php';
require 'db/connect.php';
require 'mailer/src/PHPMailer.php';
// Получите данные из POST-запроса от Яндекс.Кассы
$source = file_get_contents('php://input');
$requestBody = json_decode($source, true);
// Создайте объект класса уведомлений в зависимости от события
// NotificationSucceeded, NotificationWaitingForCapture,
// NotificationCanceled, NotificationRefundSucceeded
use YandexCheckout\Model\Notification\NotificationSucceeded;
use YandexCheckout\Model\Notification\NotificationWaitingForCapture;
use YandexCheckout\Model\NotificationEventType;
use YandexCheckout\Model\PaymentStatus;
try {
$notification = ($requestBody['event'] === NotificationEventType::PAYMENT_SUCCEEDED)
? new NotificationSucceeded($requestBody)
: new NotificationWaitingForCapture($requestBody);
} catch (Exception $e) {
// Обработка ошибок при неверных данных
}
// Получите объект платежа
$payment = $notification->getObject();
if($payment->getStatus() === PaymentStatus::SUCCEEDED) {
$payment_id = $payment->getId();
}
use PHPMailer\PHPMailer\PHPMailer;
if(isset($payment_id)) {
$email = R::getCell("SELECT `email` FROM `logs` WHERE `payment_id` = '$payment_id'");
$date = R::getCell("SELECT `date` FROM `logs` WHERE `payment_id` = '$payment_id'");
$time = R::getCell("SELECT `time` FROM `logs` WHERE `payment_id` = '$payment_id'");
$report_name = strtok("$email", '#') . ' ' . $date . ' ' . $time;
$mail = new PHPMailer();
//Set who the message is to be sent from
$mail->setFrom($email_admin, $from_name);
//Set an alternative reply-to address
$mail->addReplyTo($email_admin, $from_name);
//Set who the message is to be sent to
$mail->addAddress($email);
//Set the subject line
$mail->Subject = 'PHPMailer mail() test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$message = 'Привет ' . $report_name;
$mail->msgHTML($message);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
}
?>
I guess the problem is in logic or syntax
Let's explore what your error message says:
Fatal error: Uncaught TypeError: Argument 1 passed to YandexCheckout\Model\Notification\NotificationWaitingForCapture::__construct() must be of the type array, null given,
Argument 1 must be an array, but is given as null.
What is "argument 1"?
new NotificationWaitingForCapture($requestBody);
When a new object is instantiated it runs the __construct method, which the error references, so it is the line mentioned above, so this in turn means that $requestBody is the "Argument 1" and for whatever reason, holds a null value.
The PHP Manual states:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
This is the cause of your issue.
Suggested Fix:
You need to check your POST data is populated, rather than simply assume it is, so update your JSON_DECODE to this:
// Получите данные из POST-запроса от Яндекс.Кассы
$source = file_get_contents('php://input');
$requestBody = json_decode($source, true);
if(empty($requestBody)){
echo "POSTED data is empty! / Опубликованные данные пусты!";
exit;
}
Note that by using PHPMailer without calling isSMTP(), you are also using mail() behind the scenes.
Without more debug info, I'm going to take a flying guess at what's wrong:
You have not set your character set.
You've got Cyrillic characters in your content, but you have not changed the character set away from the default ISO-8859-1. This is very likely to result in errors.
Assuming you're using UTF-8, you need to tell PHPMailer that like this:
$mail->CharSet = 'utf-8';
It may be working with mail() when used directly because your PHP installation may be set to use UTF-8, however, PHPMailer doesn't use that as a default as it's not always available on all platforms (e.g. if the mbstring extension is disabled).
I am trying to send an email with both a calendar invite and HTML body content, but I can't seem to get the both added to the email object to be sent via SendGrid
I am able to send a calendar invite by itself and HTML body content by itself but not together.
function sendgridAPI(){
GLOBAL $mgClient,$domain,$toName, $toEmail, $fromName, $fromEmail, $subj, $body, $cc, $bcc, $attachments, $mimeMessage, $sendgrid_api_key;
$email = new \SendGrid\Mail\Mail();
$email->setFrom($fromEmail, $fromName);
$email->setSubject($subj);
$toEmails = [$toEmail => $toName,];
$email->addTos($toEmails);
if ($mimeMessage != ""){
echo "<br> 1 <br>";
$contents = [
"text/calendar" => $mimeMessage,
"text/html" => $body
];
$email->addContents($contents);
}
else{
$content = ["text/html" => $body];
$email->addContent($content);
}
if($cc != ""){
$ccEmails = [$cc => "CC",];
$email->addCcs($ccEmails);
}
if ($attachments != ""){
$filePath = $attachments;
$fileName = substr($attachments, strrpos($attachments, '/') + 1);
$fileData = base64_encode(file_get_contents($filePath));
$fileExtension = substr($attachments, strrpos($attachments, '.') + 1);
$fileType = 'application/'. $fileExtension;
$email->addAttachment(
$fileData,
$fileType,
$fileName,
"attachment"
);
$email->addAttachments($attachments);
}
$sendgrid = new \SendGrid($sendgrid_api_key);
try {
$response = $sendgrid->send($email);
$data = $response->headers();
print_r($data);
gettype($data['5']);
$responseSG = substr($data['5'], strpos($data['5'], ":") + 1);
return $responseSG;
//echo $responseSG;
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
return "";
}
}
?>
The variables are passed to this function then the email object is constructed to be sent using the SendGrid API
You need to create an attachment object for addAttachment(), not pass in a filename. And an array of Attachment objects for addAttachments()
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Mail.php#L1152-L1172
Here's the constructor for an Attachment:
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Attachment.php#L35-L52
i am trying to set html on the output of the email send by joomla. my file is located in the joomla core.
i know i have to add something like ->isHTML(true); but i do not know where and how.
here is the code:
class MailtoController extends JControllerLegacy
{
/**
* Show the form so that the user can send the link to someone.
*
* #return void
*
* #since 1.5
*/
public function mailto()
{
$session = JFactory::getSession();
$session->set('com_mailto.formtime', time());
$this->input->set('view', 'mailto');
$this->display();
}
public function send()
{
// Check for request forgeries
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$session = JFactory::getSession();
$timeout = $session->get('com_mailto.formtime', 0);
if ($timeout == 0 || time() - $timeout < 1)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
$SiteName = $app->get('sitename');
$link = MailtoHelper::validateHash($this->input->get('link', '', 'post'));
// Verify that this is a local link
if (!$link || !JUri::isInternal($link))
{
// Non-local url...
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
// An array of email headers we do not want to allow as input
$headers = array (
'Content-Type:',
'MIME-Version:',
'Content-Transfer-Encoding:',
'bcc:',
'cc:'
);
// An array of the input fields to scan for injected headers
$fields = array(
'mailto',
'sender',
'from',
'subject',
);
/*
* Here is the meat and potatoes of the header injection test. We
* iterate over the array of form input and check for header strings.
* If we find one, send an unauthorized header and die.
*/
foreach ($fields as $field)
{
foreach ($headers as $header)
{
if (strpos($_POST[$field], $header) !== false)
{
JError::raiseError(403, '');
}
}
}
/*
* Free up memory
*/
unset ($headers, $fields);
$email = $this->input->post->getString('mailto', '');
$sender = $this->input->post->getString('sender', '');
$from = $this->input->post->getString('from', '');
$subject_default = JText::sprintf('COM_MAILTO_SENT_BY', $sender);
$subject = $this->input->post->getString('subject', $subject_default);
// Check for a valid to address
$error = false;
if (!$email || !JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $email);
JError::raiseWarning(0, $error);
}
// Check for a valid from address
if (!$from || !JMailHelper::isEmailAddress($from))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $from);
JError::raiseWarning(0, $error);
}
if ($error)
{
return $this->mailto();
}
// Build the message to send
$msg = JText::_('COM_MAILTO_EMAIL_MSG');
$link = $link;
//$body = sprintf($msg, $SiteName, $sender, $from, $link);
$body = "<p>Hello Test F,</p><br/><p>Thank you for registering at Deals&offers. Your account is created and activated.</p><br/>You may login to ".$SiteName." using the following username and password:</br><p>Username: ".$sender."</p><p>Password: ".$from."/p><br/><p><b>Note:</b> It is recomended to change your password after first login. ".$link."</p>";
// Clean the email data
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
// To send we need to use punycode.
$from = JStringPunycode::emailToPunycode($from);
$from = JMailHelper::cleanAddress($from);
$email = JStringPunycode::emailToPunycode($email);
// Send the email
if (JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body) !== true)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
JFactory::getApplication()->enqueueMessage('ok!', '');
$this->input->set('view', 'sent');
$this->display();
}
}
thank you very much
you can add before body or between subject and body . however, it must be before the submit command !!
here is an example of PhpMailler firstly, you need to call the class like this and you can use it
$this->mail= new PHPMailer();
$this->mail->IsSMTP();
$this->mailIsHTML(true);
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
however if the function is static also you call the function in same class
you can call the function by sef command
self::mailIsHTML(true)
basically I am trying to get peers in php from a udp torrent tracker.
Purpose is analyzing traffic in different regions.
So I don't need to download the torrent just get the peer list and announce again to get a different set. I tried to use PHP
I have picked a open-source code that scrapes udp torrents and modified it.
here's the code
require_once(dirname(__FILE__) . '/tscraper.php');
class udptscraper extends tscraper{
/* $url: Tracker url like: udp://tracker.tld:port or udp://tracker.tld:port/announce
$infohash: Infohash string or array (max 74 items). 40 char long infohash.
*/
public function scrape($url,$infohash){
if(!is_array($infohash)){ $infohash = array($infohash); }
foreach($infohash as $hash){
if(!preg_match('#^[a-f0-9]{40}$#i',$hash)){ throw new ScraperException('Invalid infohash: ' . $hash . '.'); }
}
if(count($infohash) > 74){ throw new ScraperException('Too many infohashes provided.'); }
if(!preg_match('%udp://([^:/]*)(?::([0-9]*))?(?:/)?%si', $url, $m)){ throw new ScraperException('Invalid tracker url.'); }
$tracker = 'udp://' . $m[1];
$port = isset($m[2]) ? $m[2] : 80;
$transaction_id = mt_rand(0,65535);
$fp = fsockopen($tracker, $port, $errno, $errstr);
if(!$fp){ throw new ScraperException('Could not open UDP connection: ' . $errno . ' - ' . $errstr,0,true); }
stream_set_timeout($fp, $this->timeout);
$current_connid = "\x00\x00\x04\x17\x27\x10\x19\x80";
//Connection request
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp,$packet);
//Connection response
$ret = fread($fp, 16);
if(strlen($ret) < 1){ throw new ScraperException('No connection response.',0,true); }
if(strlen($ret) < 16){ throw new ScraperException('Too short connection response.'); }
$retd = unpack("Naction/Ntransid",$ret);
if($retd['action'] != 0 || $retd['transid'] != $transaction_id){
throw new ScraperException('Invalid connection response.');
}
$current_connid = substr($ret,8,8);
//ANNOUNCE request
$hashes = '';
$pid ='O5214m2Y0z6178K1z090';
$key = mt_rand(0,65535);
$down =mt_rand(0,12345);
$left =mt_rand(0,12345);
$upped =mt_rand(0,12345);
$transaction_id = mt_rand(0,65535);
$event = 2;
$socket = socket_create_listen (19624);
foreach($infohash as $hash){ $hashes .= pack('H*', $hash); }
$packet = $current_connid . pack("N", 1) . pack("N", $transaction_id) . $hashes . pack("N", $pid) . pack("N", $down) . pack("N", $left) . pack("N", $upped) . pack("N", 0) . pack("N", 0) . pack("N", $key) . pack("N", -1) . pack("N", 19624);
fwrite($fp,$packet);
//ANNOUNCE response
$readlength = 20 + (6 * count($infohash));
$ret = fread($fp, $readlength);
echo $ret;
if(strlen($ret) < 1){ throw new ScraperException('No .',0,true); }
if(strlen($ret) < 8){ throw new ScraperException('Too short response.'); }
$retd = unpack("Naction/Ntransid",$ret);
// Todo check for error string if response = 3
if($retd['action'] != 1 || $retd['transid'] != $transaction_id){
throw new ScraperException('Invalid scrape response.');
}
if(strlen($ret) < $readlength){ throw new ScraperException('Too short scrape response.'); }
$torrents = array();
$index = 8;
foreach($infohash as $hash){
$retd = unpack("Ninterval/Nleechers/Nseeders/Nipaddr/NTCP",substr($ret,$index));
print_r($retd);
$retd['infohash'] = $hash;
$torrents[$hash] = $retd;
$index = $index + 12;
}
return($torrents);
}
}
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80/announce',array('8B60D5838A2CE34294AF9E49FF990C5BEC6C61B1'));
//print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
?>
I am using only 1 HASH value
Some help please.
EDIT : The tracker server sometimes send the response message with peer list of peers replaced by a 6 bytes per peer. The first 4 bytes are the host IP, and the last 2bytes are port number. You should parse them to communicate with peers for pieces.
I think theory(specs) is probably not a fact. all specs about Bittorent from Internet become outdated. It might be impossible to check whether announce request is correct by just following the spec.
I recommend you to try using Wireshark. Capture packets that common Bittorent-client sends, and then check how common Bittornet client works. Compare announce request that your php code send, to one common client sends.
Actually, I'm trying to implement Bittorent client in C. I had a hard time communicating with a tracker server, since not specifying compact field in request message. But most specs says compact field in announce request is optional.
Try using wireshark. then compare two requests(your request and the other that common bittorent sends.)
I have a function to translate the current text string using the Free Bing translator API. I just want to make sure if anything fails or something happens with the Application ID or I go over on requests, I don't want a big error to show.
The code I have right now is:
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$translate = simplexml_load_string($translate_feed);
return $translate[0];
What I want to happen is if anything fails, so if I add in another character to the URL to make it invalid then I want it to just return $text so at least something shows.
Thanks!
Have you tried failing it on purpose to see what happens?
If it's an exception, just catch it and handle it...
try{
//enter code to catch
}catch(Exception $ex){
//Process the exception
}
If there is an error outputted by the function, just # to hide the error and handle the incorrect output of $translate_feed or $translate manually.
You can try failing it on purpose by simply passing an invalid URI to file_get_contents and then forcefully feed non XML or invalid XML to simplexml_load_string to see what happens.
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
if ( $translate_feed === false )
{
echo "failed";
}
You can do like this
if(#file_get_contents("yourFilePath.txt")){
echo "success";
}
/*
It's a modified file_get_contents()
get_contents(filename, use_include_path, context, offset, maxlen)
*/
function get_contents($url, $u = false, $c = null, $o = null) {
$headers = get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status == '200') {
return file_get_contents($url, $u, $c, $o);
}
return false;
}
echo get_contents('https://example.com/');
there is $http_response_header variable is being created in local scope that we can use it to check headers returned from server. Here is my implementation:
public function getData($url)
{
try {
$response = #file_get_contents($url);
if (isset($http_response_header)) {
if (!in_array('HTTP/1.1 200 OK', $http_response_header) &&
!in_array('HTTP/1.0 200 OK', $http_response_header)) {
throw new \Exception('Server did not return success header!');
}
}
return $response;
} catch (\Exception $ex) {
throw new TransportException($ex->getMessage(), $ex->getCode(), $ex);
}
}
if( !$translate_feed) return "Failed";
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$result=$text;
if ($translate_feed) {
$translate = simplexml_load_string($translate_feed);
if (is_array($translate)) $result=$translate[0];
}
return $result;