I'm trying to use the mailgun api to send user registration confirmation emails from my website. My site is on a shared host. The mailgun api seems to work perfectly, when I test it out on a localhost (WAMP server). when I try to use the api in my source code, i.e. inside a controller, I get a syntax error. The shared host is a linux based (CentOS) server.
This is the error message.
Parse error: syntax error, unexpected '[' in /var/www/html/log2pdf/mailgun/vendor/guzzlehttp/psr7/src/functions.php on line 78
Since it was a syntax error, I downloaded and installed the mailgun dependancies (i.e. composer, guzzle adapter etc.) separately on the linux server, because I had originally copied the files from my localhost (windows) and was under the
impression that these files are different for windows and linux. But that made no difference either.
Running php 5.6.25 on localhost (WAMP), php 5.3.3 on shared host(CentOS). All the mailgun dependencies were installed using the commands on the mailgun webpage.
I have tried all that I could, any help on this will be greatly appreciated.
This is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require '/var/www/html/mysite/mailgun/vendor/autoload.php';
use Mailgun\Mailgun;
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('User_model');
$this->load->helper('cookie');
}
public function index($param = '')
{
if (($this->session->userdata('userLogin') == TRUE))
{
redirect(site_url('users/dashboard')); }
if (isset($_POST['registration'])){
$data['postdata'] = $_POST;
if(!empty($_POST['firstname']) && !empty($_POST['lastname']) &&
!empty($_POST['email']) && !empty($_POST['password']) &&
!empty($_POST['organization']) && !empty($_POST['country']) &&
!empty($_POST['address'])){
$checkEmail = $this->User_model->checkEmail();
if($checkEmail==true){
$this->session->set_flashdata('error', '<p><font>
This Email id is already registered!</font></p>');
}else{
$un = str_replace(' ', '',$_POST['firstname'].$_POST['lastname']);
//remove all spaces
$unwsc = preg_replace('/[^A-Za-z0-9\-]/', '', $un);
// Removes special chars.
$checkusername = $this->User_model->checkusername($unwsc);
if($checkusername==true){
$username = $this->getUserName($unwsc);
}else{
$username = $unwsc;
}
$data['code'] = rand(0,100000);
$data['username'] = $_POST['firstname'];
$this->User_model->saveUser($username,$data['code']);
mkdir("/var/www/html/users/".$username);
/*
$fromemail="_my_organisation's_email_";
$subject = "Registration Confirmation";
//this was the email sender that i used initially
//it's codeigniter's built in email library. but after a
//while, emails stopped being delivered.
$this->load->library('email');
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->to($_POST['email']);
$this->email->from($fromemail, "_my_organisation's_email_");
$this->email->subject($subject);
$body = $this->load->view('email/register.php',$data,TRUE);
$this->email->message($body);
$this->email->send();
*/
$subject = "Registration Confirmation";
$body = $this->load->view('email/register.php',$data,TRUE);
//using mailgun api
# Instantiate the client.
$mgClient = new Mailgun('_my_mailgun_key_');
$domain = "_my_maigun_domain_";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'NO REPLY <_my_organisation's_email_>',
'to' => 'new user <_authorized_recipient_>',
'subject' => 'Mailgun test',
'text' => 'testing email sender'
));
$this->session->set_flashdata('success','<p><font>Thanksfor registration! </font></p>');
redirect(site_url('register/complete'));
}
}else{
$this->session->set_flashdata('error', '<p><font>
Missing Some Fields!</font></p>');
}
}
$data['title']='';
$data['param']=$param;
$this->load->view('registration/index',$data);
}
function getUserName($string) {
$result = $string;
for ($i = 1; $i < 100; $i++) {
$userChecking = $this->User_model->checkusername($string.$i);
if(empty($userChecking)){
$result = $string.$i;
break;
}
}
return $result;
}
}
?>
The problem was solved after updating PHP to version 5.6.30. After a long duration of talk with Godaddy's customer support, They suggested that I update my PHP. It worked perfectly after.
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have a cron job set up on my hostgator server that returns a value of 1 (email sent), but doesn't actually send the email. When I call the php file manually in the browser, the email gets sent. It doesn't if run via cron.
Earlier this month, I moved my site from one server on hostgator to another server (on hostgator) so I could get SSL and a dedicated IP address. Since moving the site, the cron jobs work OK except for the part that sends the email (ie, database functions work fine). I've contacted hostgator tech support, but he thinks the problem is in my code.
Thinking that maybe my server info was incorrect, I switched to using smtp.gmail.com and using a gmail account to send the mail, but that didn't work either. Please help!
The cron job is set up like this:
* 7 * * * /opt/php56/bin/php /home/user/public_html/somefolder/sendmailcron.php
(While testing, I changed it to run every 2 minutes: */2 * * * * )
Here's the sendmailcron.php script:
<?php
$now = date("Y-m-d H:i:s");
$msgcontent = [];
$msgcontent['email'] = "recipient#example.com";
$msgcontent['name'] = "Recipient Name";
$msgcontent['textpart'] = "This is the text version of the email body.";
$msgcontent['htmlpart'] = "<p>This is the <strong>HTML</strong> version of the email body.</p>";
$msgcontent['subject'] = "Test email sent at " . $now;
$result = sendMyMail($msgcontent, "HTML");
exit();
function sendMyMail($msgcontent, $format="HTML") {
require_once '/home/user/public_html/somefolder/swiftmailer/lib/swift_required.php';
$result = 0;
$subject = $msgcontent['subject'];
$email = $msgcontent['email'];
if (strlen($email) == 0) {
return 0;
}
$name = $msgcontent['name'];
$emailbody = $msgcontent['textpart'];
$emailpart = $msgcontent['htmlpart'];
switch($format) {
case "TEXT":
$msgformat = 'text/plain';
break;
case "HTML":
$msgformat = 'text/html; charset=UTF-8';
break;
default:
$msgformat = 'text/html';
break;
}
$adminemailaddress = "me#mydomain.com";
$adminemailpwd = 'myadminpwd';
$sendername = 'My Real Name';
$transport = Swift_SmtpTransport::newInstance('mygator1234.hostgator.com', 465, "ssl")
->setUsername($adminemailaddress)
->setPassword($adminemailpwd)
;
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
if($format == "TEXT") {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailbody)
->setContentType($msgformat)
;
}
else {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailpart)
->setContentType($msgformat)
;
}
//This is where we send the email
try {
$result = $mailer->send($message); //returns the number of messages sent
} catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
return $result; //will be 1 if success or 0 if fail
}
?>
The return value is always 1, but no email is sent.
Any suggestions would be greatly appreciated!
Your cron job uses a different php.ini configuration file, than your browser uses.
Try running the cron job by disabling safe_mode, like this:
/opt/php56/bin/php -d safe_mode=Off /home/user/public_html/somefolder/sendmailcron.php
And check if the email is now sent.
I am having issue to send messages via WhatsApp PHP Client. Details given below:
Error
Due to length it's given here: http://pastie.org/10794465
```
Debug log
http://pastie.org/10794474
Code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
set_time_limit(10);
var_dump(extension_loaded('curve25519'));
var_dump( extension_loaded('protobuf'));
//require_once __DIR__.'../vendor/whatsapp/autoload.php';
date_default_timezone_set('Europe/Madrid');
//require_once __DIR__.'../vendor/whatsapp/chat-api/src/whatsprot.class.php';
require_once 'vendor/whatsapp/chat-api/src/whatsprot.class.php';
require_once 'vendor/whatsapp/chat-api/src/events/MyEvents.php';
//require_once __DIR__.'/../src//events/MyEvents.php';
$username = '92xxxxxxxxx'; // Telephone number including the country code without '+' or '00'.
$password = 't7+YzhqpUd8P7LgeU9NdttaIpc4='; // Use registerTool.php or exampleRegister.php to obtain your password
$nickname = 'ADD Agent'; // This is the username (or nickname) displayed by WhatsApp clients.
$target = "92xxxxxxxxx"; // Destination telephone number including the country code without '+' or '00'.
$target = "92xxxxxxxxx"; // Destination telephone number including the country code without '+' or '00'.
$debug = true; // Set this to true, to see debug mode.
echo "[] Logging in as '$nickname' ($username)\n";
//Create the whatsapp object and setup a connection.
$w = new WhatsProt($username, $nickname, $debug,true,__DIR__.'/wadata/');
$events = new MyEvents($w);
$events->setEventsToListenFor($events->activeEvents);
$w->connect();
// Now loginWithPassword function sends Nickname and (Available) Presence
$w->loginWithPassword($password);
$w->sendMessage($target, 'Salam kia haal hain?!');
echo "<b>Message Sent to $target</b>";
echo "<br>Getting message<br>";
$w->pollMessage();
$msgs = $w->GetMessages();
foreach ($msgs as $m) {
var_dump($m);
}
In MyEvents.php
public function onGetMessage( $mynumber, $from, $id, $type, $time, $name, $body )
{
echo "<br>Message Got from $name:\n$body\n\n<br>"; // NOT being fired.
exit;
}
To receive message you need bind onGetMessage and call pollMessage in a loop
while (1) {
$w->pollMessage();
}
Check this example complete:
<?php
//set_time_limit(10);
require_once __DIR__.'/../src/whatsprot.class.php';
require_once __DIR__.'/../src//events/MyEvents.php';
//Change to your time zone
date_default_timezone_set('Europe/Madrid');
//######### DO NOT COMMIT THIS FILE WITH YOUR CREDENTIALS ###########
///////////////////////CONFIGURATION///////////////////////
//////////////////////////////////////////////////////////
$username = '*************'; // Telephone number including the country code without '+' or '00'.
$password = '*************'; // Use registerTool.php or exampleRegister.php to obtain your password
$nickname = 'LuisN'; // This is the username (or nickname) displayed by WhatsApp clients.
$target = "************"; // Destination telephone number including the country code without '+' or '00'.
$debug = false; // Set this to true, to see debug mode.
///////////////////////////////////////////////////////////
function onPresenceAvailable($username, $from)
{
$dFrom = str_replace(['#s.whatsapp.net', '#g.us'], '', $from);
echo "<$dFrom is online>\n\n";
}
function onPresenceUnavailable($username, $from, $last)
{
$dFrom = str_replace(['#s.whatsapp.net', '#g.us'], '', $from);
echo "<$dFrom is offline> Last seen: $last seconds\n\n";
}
function onGetMessage($mynumber, $from, $id, $type, $time, $name, $body){
echo sprintf("Message from %s: [%s]\r\n",$from,$body);
}
echo "[] Logging in as '$nickname' ($username)\n";
// Create the whatsapp object and setup a connection.
$w = new WhatsProt($username, $nickname, $debug);
$w->connect();
// Now loginWithPassword function sends Nickname and (Available) Presence
$w->loginWithPassword($password);
$w->sendGetServerProperties();
$w->sendGetGroups();
$w->sendGetBroadcastLists();
// Set the profile picture
//$w->sendSetProfilePicture(Constants::PICTURES_FOLDER . '/314484_300x300.jpg');
$w->sendStatusUpdate("La vida es un carnaval \xF0\x9F\x8E\xB6");
// Synchronizes contacts with the server, very important to avoid bans
$w->sendSync([$target]);
// Print when the user goes online/offline (you need to bind a function to the event onPressence
// so the script knows what to do)
$w->eventManager()->bind('onPresenceAvailable', 'onPresenceAvailable');
$w->eventManager()->bind('onPresenceUnavailable', 'onPresenceUnavailable');
// Receives and processes messages, this includes decrypted
$w->eventManager()->bind('onGetMessage','onGetMessage');
echo "[*] Connected to WhatsApp\n\n";
$w->sendMessage($target, 'Guess the number :)');
$w->sendMessage($target, 'Sent from WhatsApi at '.date('H:i'));
while (1) {
$w->pollMessage();
}
PD: I tested this method in 3 environments
php 5.5 Cli NTS VC11 Windows 10
php 5.5 Cli NTS VC11 Windows 7
PHP 5.5.9-1ubuntu4.14 Cli
I'm trying to send mail for a contact form locally by swiftmailer and gmail. I've checked every line and I know the problem is 'setFrom' .
$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();
$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];
if(!empty($name) && !empty($email) && !empty($msg) ){
$cleanName = filter_var($name,FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($name,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($name,FILTER_SANITIZE_STRING);
}else {
//redirecting to contact page
}
//sending email
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('xxx#gmail.com')
->setPassword('xxx');
$mailer= \Swift_Mailer::newInstance($transporter);
$message = \Swift_Message::newInstance();
$message->setSubject('Email from our website');
$message->setTo(array('ns.falahian#gmail.com'));
$message->setBody($cleanMsg);
$message->setFrom([
$cleanEmail => $cleanName
]);
$result=$mailer->send($message);
if ($result > 0) {
$path = $this->get('router')->pathFor('home');
return $response->withRedirect($path);
} else {
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
}
});
as you can see I also use Slim 3 framework. when I run the code I get this error:
Slim Application Error
A website error has occurred. Sorry for the temporary inconvenience.
But if I replace the $cleanEmail with 'x#y.z' the code works!
what should I do?
I know that by using gmail I can't change the sender name but I want to upload this code in a webhost and I don't want to get this issue there.
And can anyone suggest a better way for redirecting in Slim 3? Instead of these two lines:
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
I've set names for my routes like this:
$app->get('/contact', function ($req, $res, $args) {
return $this->view->render($res, "contact.twig");
})->setName('contact');
thanks a lot!
You probably want to do the following instead.
$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg,FILTER_SANITIZE_STRING);
I'm trying to write a simple Constant Contact script for adding and updating emails. The script is simple enough and should've ran smoothly. But when I start to include 'src/Ctct/autoload.php' the page just returns blank. I tried running it on another server and it works. But on my working server, it returns blank. It uses OAuth authentication from CTCT. I think it's a setting in the server, but I have no control over the server and any changes need to be forwarded to an admin, I just don't know what I need to change.
Here's the code:
require "Scripts/ConstantContact/src/Ctct/autoload.php";
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;
define("APIKEY", "*** Censored Media (18+ only) ***");
define("ACCESS_TOKEN", "*** Censored Media (18+ only) ***");
$cc = new ConstantContact(APIKEY);
// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
$lists = $cc->getLists(ACCESS_TOKEN);
$action = "Getting Contact By Email Address";
$Email = "asdf#asdf.com";
$FirstName = "Asdf";
$LastName = "Ghjk";
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $Email);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($Email);
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact);
}
// catch any exceptions thrown during the process and print the errors to screen
if (isset($returnContact)) {
echo '<div class="container alert-success"><pre class="success-pre">';
print_r($returnContact);
echo '</pre></div>';
}
print '<p>'.$action.'</p>';
Again, this works on another server I tried, but doesn't work on my working server.
Any help would be appreciated.
Thanks!
Are you running PHP 5.3 or higher on the other server? Also did the domain change at all, if so that may throw an exception resulting in a blank page as your API key is domain specific. Feel free to shoot me an email and I will be glad to help you out with this - mstowe [at] constantcontact.com
-Mike
I have this weird error coming up from phpmailer (Version: 5.1 ):
exception 'phpmailerException' with message 'Could not instantiate mail function.' in C:\Inetpub\vhosts\mydomain\httpdocs\myscript\protected\components\phpmailer\class.phpmailer.php:687 Stack trace: #0 C:\Inetpub\vhosts\mydomain\httpdocs\myscript\protected\components\phpmailer\class.phpmailer.php(578): PHPMailer->MailSend('Date: Wed, 2 Oc...', '--b1_3c2b33630c...')
FYI: I am trying to send a zip file that's around 4.5MB big. But before that the script generates around 50 PDFs and adds them/creates the zip file which then gets attached to a phpmailer object and sent. (I am not using SMTP).
I know this has been asked before.. but the solutions I have found are all based on linux server involving increasing the limit on postfix.
But how do I solve this issue if the site is hosted on a windows machine ? I have plesk control panel.
Thanks in advance for your help.
[EDIT]
Here's the code snippet just incase it helps:
foreach($vars as $PDFKEY)
{
if($PDFKEY != null)
{
if((int)$PDFKEY > 0 )
{
$filename = $this->CreatePDF($PDFKEY);
$emailarr[$PDFKEY['email']][] = $filename;
$emailIdarr[$company->email][] = $PDFKEY['email'];
}
}
}
sleep(20);
//print_r($emailarr);die;
$emailTemplate = Yii::app()->params['EmailTemplate'];
$body = file_get_contents($emailTemplate);
$body = eregi_replace("[\]",'',$body);
try
{
$mail = new PHPMailer(true);
if(strtolower(Yii::app()->params['SMTPStatus']) == "enabled")
{
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = Yii::app()->params['SMTPHost']; // sets the SMTP server
$mail->Port = Yii::app()->params['SMTPPort']; // set the SMTP port for the GMAIL server
if(strtolower(Yii::app()->params['SMTPAuthStatus']) == "enabled")
{
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Username = Yii::app()->params['SMTPUsername']; // SMTP account username
$mail->Password = Yii::app()->params['SMTPPassword']; // SMTP account password
}
}
$mail->SetFrom(Yii::app()->params['EmailSendFrom']);
$mail->AddReplyTo(Yii::app()->params['EmailSendFrom']);
$mail->Subject = Yii::app()->params['EmailSubject'];;
$savePath = Yii::app()->params['PdfSavePath'];
$mail->AddBCC(trim(Yii::app()->params['EmailBCC']));
$b = true;
$toEmailAdded = array();
$ccEmailAdded = array();
$companyCCEmailAdded = array();
foreach($emailarr as $email=>$attachmentArr )
{
try
{
if(!in_array($email, $toEmailAdded))
{
$toEmailAdded[] = $email;
$mail->AddAddress($email);
}
if(isset($_POST['emailcc']) && strlen($_POST['emailcc']) > 0)
{
if(!in_array($_POST['emailcc'], $ccEmailAdded))
{
$ccEmailAdded[] = trim($_POST['emailcc']);
$mail->AddCC(trim($_POST['emailcc']));
}
}
$companycc = trim($emailNamearr[$email]['companyccemail']);
if(isset($companycc) && strlen($companycc) > 0)
{
foreach(explode(',',trim($companycc)) as $cc)
{
if(!in_array($cc, $companyCCEmailAdded))
{
$companyCCEmailAdded[] = trim($cc);
$mail->AddCC(trim($cc));
}
}
}
if(count($attachmentArr) > 1)
{
$zipFileName = "Archieve-".uniqid().".zip";
if($this->create_zip($attachmentArr, $zipFileName, true)) {
$mail->AddAttachment($SavePath.$zipFileName); // attachment
sleep(20);
}
} else
{
foreach($attachmentArr as $attachment)
{
$mail->AddAttachment($SavePath.$attachment); // attachment
}
}
$msgbody = str_replace("<%EMAILSENTDATE%>", date('d/m/Y', strtotime($emailNamearr[$email]['serviced'])) , $body );
if(isset($emailNamearr[$email]))
{
$msgbody = str_replace("<%CLIENTNAME%>", "for ".$emailNamearr[$email]['company'] , $msgbody );
}
else $msgbody = str_replace("<%CLIENTNAME%>", "" , $msgbody );
$mail->MsgHTML($msgbody);
try
{
$mail->Send();
}catch(Exception $e)
{
echo "<br/><br/>$e<br/><br/>".$e;die;
}
//echo "$email <br/>";
$mail->ClearAddresses();
$mail->ClearAttachments();
$mail->ClearCCs();
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
$b = false;
}
}
}
After tearing out quite a bit of hair on my head I think I kind of sort out the issue. Here's what I did (in case anyone else is facing the same problem )
Under IIS->My Website->error pages->Edit Features Settings By default Detailed errors for local request is selected for security purposes.
This threw the 500 error but the actual cause was hidden. By changing it to "Detailed errors" the actual error was revealed which was :
"FastCGI process exceeded" I believe by default it's 30 secs.
So even though I've max_execution_limit = 300 the process was getting stopped/failed because of the php-cgi.exe 's execution time limit.
To solve this:
edit %windir%\system32\inetsrv\config\applicationHost.config file to extend the php-cgi.exe execution time limit. set activityTimeout:3600 and requestTimeout:3600 .. i set 3600 to be on safe side and because i could.
And then the application ran just fine.
Hope this helps saving the hair on head for someone.
I think:
Yii::app()->params['SMTPStatus'] is not 'enabled'
so phpmailer uses php native mail function witch, I think, is not configured in your php.ini
Hope this helps