This is driving me nuts.
Downloaded and installed ZendFramework. Trying to send a DKIM signed mail but it is giving me this error(which i copied directly off their documentation).
Error: Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\Project\send_form_email.php:12 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Project\send_form_email.php on line 12
// sign message with dkim
$signer = $this->getServiceLocator()->get('DkimSigner');
$signer->signMessage($mail);
What am I doing wrong here?
Edit: Added all coding
<?php
require 'vendor/autoload.php';
$mail = new \Zend\Mail\Message();
$mail->setBody("Test world!");
$mail->setFrom('noreplytest#sanscalc.co.za');
$mail->addTo('jr.swart49995#gmail.com');
$mail->setSubject('le subject');
// sign message with dkim
$signer = $this->getServiceLocator()->get('DkimSigner');
$signer->signMessage($mail);
// send message
$transport = new \Zend\Mail\Transport\Sendmail();
$transport->send($mail);
?>
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
$this is only valid when called from inside an object. Your code is not within an object, which is why calling $this throws the error.
$this->getServiceLocator()->get('DkimSigner');
your code is expecting to call a getServiceLocator() method defined within an object, which you have not done as your code is more procedural in nature.
I am guessing you're trying to use the example code from here: https://github.com/joepsyko/zf-dkim
If you check that page it tells you the code should be within a controller (object) where $this is in a valid context, and also where the getServiceLocator method is defined.
try and Install the standard "getting started" zend framework and try the snippet within a controller (https://docs.zendframework.com/tutorials/getting-started/skeleton-application/)
or do away with the use of the service locator in your code and instantiate the DKimm Signer yourself within your script manually.
I am trying to connect to a service bus queue in Microsoft Azure using PHP, using the following code found on the Azure guide:
<?php
require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Queue\QueueRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Queue\Models\CreateMessageOptions;
$connectionString = "DefaultEndpointsProtocol=https;AccountName="name";AccountKey=key";
// Create queue REST proxy.
$queueClient = QueueRestProxy::createQueueService($connectionString);
try{
// Create message.
$builder = new ServicesBuilder();
$queueClient->createMessage("cmps297r1", "Hello World!");
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179446.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
?>
However, when I run it, I get this error:
Catchable fatal error: Argument 4 passed to MicrosoftAzure\Storage\Common\Internal\ServiceRestProxy::__construct() must be an instance of MicrosoftAzure\Storage\Common\Internal\Serialization\ISerializer, array given, called in /Applications/XAMPP/xamppfiles/htdocs/297R/vendor/microsoft/azure-storage/src/Queue/QueueRestProxy.php on line 110 and defined in /Applications/XAMPP/xamppfiles/htdocs/297R/vendor/microsoft/azure-storage/src/Common/Internal/ServiceRestProxy.php on line 77
The code you pasted looks fine to me (except that you didn't include use statement for ServicesBuilder class which would cause an "Class not found" error).
And as #Thuan Ng mentioned the code above belongs to Azure Storage Queue, not Service Bus Queue. You need to refer to this documentation How to use Service Bus queues with PHP if you are using Azure Service Bus.
I Know this is an old Post but you are trying to create a storage queue and not a service bus queue
I am running application well in yii2. I created a command controller /commands/TestController
<?php
namespace app\commands;
use app\models\UserProfile;
use yii\console\Controller;
use app\controllers\AppController;
/**
* Test controller
*/
class TestController extends Controller
{
public function actionIndex()
{
echo "cron service running";
}
public function actionSendBirthdaySms()
{
$userProfile = UserProfile::find()
->where('MONTH(dob) = MONTH(DATE(NOW()))')
->andWhere('DAY(dob) = DAY(NOW()) ')
->with('user')
->asArray()
->all();
foreach($userProfile as $item){
$birthdayMessage = "Happy Birthday " . $item['user']['username'];
//to send sms
$this->_send_cron_sms($item['mobile'], $birthdayMessage);
}
}
I have two functions here. When I call php /home/user/public_html/yii test/index it gives the correct output with command line and cron both.
But when I am running php /home/user/public_html/yii test/send-birthday-sms, it runs OK with command line in ssh environment and I am receiving the SMS. But giving error in cron. Here is what I received in email:
Status: 500 Internal Server Error
X-Powered-By: PHP/5.4.39
Content-type: text/html
PHP Fatal Error 'yii\base\ErrorException' with message 'Class 'PDO' not found'
in /home/user/public_html/vendor/yiisoft/yii2/db/Connection.php:609
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}
I also tried query builder but it also did not helped me.
I have solved the issue by adding these two extensions in php.ini file
extension=pdo.dll
extension=pdo_mysql.dll
I already asked the same question in Yii forum
This is probably pretty basic for Slim, or maybe even a php issue, but I have no idea why it's not working:
$body = $app->request->getBody();
syslog(LOG_INFO,$body);
$app->put('/contacts',function(){
try {
$body = $app->request->getBody();
syslog(LOG_INFO,"contacts received: ".json_decode($body));
} catch(Exception $ex){
syslog(LOG_ERR,$ex);
}
});
The first log gets the body, but when i get to the second one i get this error:
exception 'ErrorException' with message 'Undefined variable: app'
same thing happens when I try commenting out the one in the put request and try to read the $body
exception 'ErrorException' with message 'Undefined variable: body'
You have to pass it in like this:
$app->put('/get-connections',function() use ($app) {
Why this is not obvious in the documentation I do not know.
For a project (which is about estate properties) i have included a contact form where a visitor can contact an estate broker if the visitor is interested to buy/hire an estate property.
I am using Symfony2 and its library. For the contact mail, i am using the Swiftmailer library.
Well, i have the next code which handles the form submit. there, I create a mail object to be able to send mails. It works, but i want to provide a error resolving service if there are problems with the smtp host from sender/receiver.
Here is the code,
$data = $contactForm->getData();
try {
// create body text
$body = $app['twig']->render('mailTemplate.twig', array('data' => $data, 'immoid' => $immoID));
// set mail
$mail = \Swift_Message::newInstance()
->setSubject('Contact reaction on your immo offer.')
->setFrom($app['swiftconfig']['sender'])
->setTo($contactinfo['contactmail'])
->setBody($body, 'text/html');
// send mail
$app['mailer']->send($mail);
// redirect if successfull
$app->redirect($app['url_generator']->generate('immoDetail', array('immoID' => $immoID)));
}
catch (Swift_TransportException $STe) {
// logging error
$string = date("Y-m-d H:i:s") . ' - ' . $STe->getMessage() . PHP_EOL;
file_put_contents("errorlog.txt", $string, FILE_APPEND);
// send error note to user
$errorMsg = "the mail service has encountered a problem. Please retry later or contact the site admin.";
}
catch (Exception $e) {
// logging error
$string = date("Y-m-d H:i:s") . ' - GENERAL ERROR - ' . $e->getMessage() . PHP_EOL;
file_put_contents("errorlog.txt", $string, FILE_APPEND);
// redirect to error page
$app->abort(500, "Oops, something went seriously wrong. Please retry later !");
}
($app['swiftconfig']['sender'] = mailaddress from host / $contactinfo['contactmail'] = mailaddress from site visitor (submitted in contact form))
Now, when the smtp host doesn't work, Swiftmailer DOES send an exception, but the try-catch block ISN'T catching it. The function is just being continued.
Even the root try-catch block (in app.php) isn't catching it too. As a result of this, you see a large PHP error on the webpage, which shouldn't happen. The message from it is described here below,
SCREAM: Error suppression ignored for
---
Fatal error: Uncaught exception 'Swift_TransportException' with message ' in C:\...\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php on line 266
---
Swift_TransportException: Connection could not be established with host <output omitted>
Does anyone know why the try catch block isn't catching the custom exception ? I have investigated the class files and the progress, but i don't see any unusual activity.
I hope that someone can come with a solution to this because PHP errors shouldn't appear on site pages.
remove from your config.yml
spool: { type: memory }
Then you will be to add try catch like this
try{
$mailer = $this->getMailer();
$response = $this->getMailer()->send($message);
}catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
Try to put a backslash infront of Exception.
catch(\Exception $e)
A \ (backslash) before the beginning of a class name represents the Global Namespace.
Using a backslash will ensure that the Exception is called within the global namespace.
When you do $app['mailer']->send($mail); the email message is not being sent at that point if you have spooling turned on. See http://symfony.com/doc/current/cookbook/email/spool.html
If you have the default setting of spool: { type: memory }, the \Swift_TransportException will be thrown during the kernel termination phase, after you controller has exited.
One way around this is to turn off the spooling (but then your users might have to wait while the email is sent), or you can make your own eventlistener to handle the exception. http://symfony.com/doc/current/cookbook/service_container/event_listener.html
I ran into this problem in Laravel 4.2 when I added a SwiftMailerHandler to Monolog so it would email to me anything logged at a certain level or above. There was no way for me to catch the exception in the handler and it was thrown back to the browser. I solved it by subclassing SwiftMailerHandler:
<?php
/*******************************************************************************
* $Id: LogMailer.php 12152 2015-09-15 00:42:38Z sthames $ */
/**
* Subclass of Monolog SwiftMailerHandler that will catch exceptions SwiftMailer
* throws during the send. These exceptions are logged at the critical level.
* Without this, such exceptions are reported back to the browswer.
*******************************************************************************/
class LogMailer extends \Monolog\Handler\SwiftMailerHandler
{
/** Flag set when logging an exception during send. */
protected $dont_mail = false;
/** Overloads sender to catch and log errors during the send. */
protected function send($content, array $records)
{
try
{
if (!$this->dont_mail)
parent::send($content, $records);
}
catch(\Exception $e)
{
$this->dont_mail = true;
Log::critical($e->getMessage());
$this->dont_mail = false;
}
}
}
This handler catches the SwiftMailer exception and logs it at the critical level so it's not lost. I don't get an email about it but at least it's in the log.
I was surprised to find SwiftMailerHandler offered no way to inject an exception handler into the send method but fortunately the code is written well enough to make this solution pretty simple.
Works great and has given me no trouble so far.
Sure you have the latest version of swiftmailer? Line 226 of StreamBuffer.php doesn't throw any exception. This version from 2 years ago does throw the exception on that specific line.
I'd try running the latest version before diving into the issue more deeply.
SCREAM is a setting of XDebug that allows to see errors that are normally caught or suppressed. (Using #, for example.) Search for
xdebug.scream = 1
in your php.ini and set this to 0.
you can try below code for custom error:
public function render($request, Exception $exception)
{
if ($exception instanceof \Swift_TransportException) {
return response()->view('errors.404');
}
return parent::render($request, $exception);
}