"An error occurred while handling another error: yii\web\HeadersAlreadySentException" - php

I am trying to submit a comment on a guestbook application based on the Yii 2 Framework. On localhost on my PC works everything fine, but on the shared hosting when I want to submit a comment in View, I get this error.
Here is the error:
An error occurred while handling another error:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send()
#2 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send()
#2 /home/mahdikas/public_html/guestbook/web/index.php(12): yii\base\Application->run()
#3 {main}
In the postController I have this code:
public function actionAdd_comment()
{
//print_r($_POST);
$model = new \app\models\Comments;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->comment_date = date('Y-m-d H:i:s');
if ($model->save()) {
echo 'Thanks for your comment.';
} else {
echo 'Failed!';
}
}
}
which line 117 in the error is:
echo 'Thanks for your comment.';
How can I solve this problem?

Since Yii 2.0.14 you cannot echo in a controller. A response must be returned:
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->comment_date = date('Y-m-d H:i:s');
if ($model->save()) {
return 'Thanks for your comment.';
} else {
return 'Failed!';
}
}
}
You may also call exit at the end of your method to prevent further processing or wrap your code with ob_start() and ob_get_clean(), if you're not able to avoid echo.
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$this->someMagicWithEcho();
exit;
}
}
or
public function actionAdd_comment() {
$model = new \app\models\Comments();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
ob_start();
$this->someMagicWithEcho();
return ob_get_clean();
}
}

Although I accept rob006's solution as correct, I have encountered a situation where there was no echo in the controller, but I also got the error. After going through several sites looking for a solution, I discovered an alternative.
You can check the php.ini file and ensure the output buffer is enabled. If not, you can enable it by adding this line in php.ini if it does not exist:
output_buffering = on
And turn it off for just the script - the script where it is not required by either...
calling ob_end_flush(), or
calling ob_end_clean()

Related

PHP Exceptions CodeIgniter

my code is generating ssse following error:
Fatal error: Uncaught TypeError: Argument 1 passed to
CI_Exceptions::show_exception() must be an instance of Exception,
instance of Error given, called in
C:\xampp\htdocs\gog\lib\core\Common.php on line 662 and defined in
C:\xampp\htdocs\gog\lib\core\Exceptions.php:190 Stack trace: #0
C:\xampp\htdocs\gog\lib\core\Common.php(662):
CI_Exceptions->show_exception(Object(Error)) #1 [internal function]:
_exception_handler(Object(Error)) #2 {main} thrown in C:\xampp\htdocs\gog\lib\core\Exceptions.php on line 190
The line of the codes described is these:
function _exception_handler(Throwable $exception)
{
$_error =& load_class('Exceptions', 'core');
$_error->log_exception('error', 'Exception: '.$exception->getMessage(), $exception->getFile(), $exception->getLine());
// Should we display the error?
if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
{
$_error->show_exception($exception); //line 662
}
exit(1); // EXIT_ERROR
}
public function show_exception(Exception $exception) //line 190
{
$templates_path = config_item('error_views_path');
if (empty($templates_path))
{
$templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
}
$message = $exception->getMessage();
if (empty($message))
{
$message = '(null)';
}
if (is_cli())
{
$templates_path .= 'cli'.DIRECTORY_SEPARATOR;
}
else
{
set_status_header(500);
$templates_path .= 'html'.DIRECTORY_SEPARATOR;
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include($templates_path.'error_exception.php');
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
}
Someone can pinpoint my problem ?
No CodeIgniter version has that _exception_handler() signature. This is what happens when you modify stock framework files.
Download a fresh copy of the latest CodeIgniter and replace yours with it.
You call show_exception(Exception $exception) from within _exception_handler(Throwable $exception). Since the former takes an Exception as argument, you cannot give it a Throwable, as you do in line 662. Exception implements the Throwable interface, but that does not guarantee all Throwables to be Exceptions (e. g. they could be of type Error).
Replace _exception_handler(Throwable $exception) with _exception_handler(Exception $exception), or change show_exception(Exception $exception) to show_exception(Throwable $exception), and change the method bodies accordingly if needed.

I suddenly get a fatal error. I don't understand it

I have been working at a code that used to work. However, suddenly, this message pops up.
Fatal error: Uncaught exception 'Exception' with message 'Email is incorrect!' in C:\xampp\htdocs\Prototype\classes\User.php:23
Stack trace: #0 C:\xampp\htdocs\Prototype\index.php(14): User->setEmail(true) #1 {main} thrown in C:\xampp\htdocs\Prototype\classes\User.php on line 23
But I just don't understand what this means. I tried using try and catch, but it keeps popping up.
This is the code where the error occurs
public function setEmail($p_email)
{
if (empty($p_email)) {
throw new Exception('Email kan niet leeg zijn!');
}
$this->email = $p_email;
if (!filter_var($p_email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Email is incorrect!'); //here is the error (line 23)
}
}
this is the code where it is summoned
$user = new User();
$user->setEmail($_SESSION['login']); //line 14
$currentUser = $user->getProfile();
$userEmail = $user->getEmail();
$userName = $user->getUserName();
$userID = $currentUser['userID'];
Your error is that you are passing a boolean instead of a valid string email...
Stack trace: #0 C:\xampp\htdocs\Prototype\index.php(14): User->setEmail(true) #1 {main} thrown in C:\xampp\htdocs\Prototype\classes\User.php on line 23
So, this line is incorrect:
$user->setEmail($_SESSION['login']); //line 14

phpmailerException with message 'Invalid address'

I am new to PHPMailer. It is working well on my localhost but not on live.
I get this error:
Fatal error: Uncaught exception 'phpmailerException' with message 'Invalid address: ' in /directoryhere/test/public_html/scripts/phpmailer/class.phpmailer.php:498 Stack trace: #0 /directoryhere/test/public_html/scripts/phpmailer/class.phpmailer.php(438): PHPMailer->AddAnAddress('to', '', '') #1 /directoryhere/test/public_html/scripts/include.php(189): PHPMailer->AddAddress('', '') #2 /directoryhere/test/public_html/forgot.php(49): send_mail() #3 /directoryhere/test/public_html/index.php(141): include('/home1/test...') #4 {main} thrown in /directoryhere/test/public_html/scripts/phpmailer/class.phpmailer.php on line 498
This is the line of code
/directoryhere/test/public_html/scripts/phpmailer/class.phpmailer.php:498:
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
if ($this->SMTPDebug) {
echo $this->Lang('invalid_address').': '.$address;
}
return false;
}
/directoryhere/test/public_html/scripts/phpmailer/class.phpmailer.php(438):
public function AddAddress($address, $name = '') {
return $this->AddAnAddress('to', $address, $name);
}
Could anyone help me what may be the possible cause of this?
#Synchro #m02ph3u5 Thank you for pointing that out! It is working well now. The problem is in the submit code . The email value is empty and yet the submit button is firing when the page loads. So what I did is to load first the form, catch if email input was empty, if not empty then the submit button was enable and ready to fire.
I just added this code of line here before the submission and calling the mail function:
if(isset($_POST["retrieve"])) { //name of button
//submission and calling mail function here
}

'Invalid header value detected' when trying to fetch email with Zend_Mail_Storage_Imap

I am trying to receive emails with Zend_Mail_Storage_Imap but keep getting 'Invalid header value detected' on some e mails.
I have located the header which is causing the crash to the following:
Content-Type: application/vnd.oasis.opendocument.text;
name="=?UTF-8?Q?cc-demo-minutes-2014-09-09_-_=c3=a5_detta_=c3=a4r_en_kopia?=
=?UTF-8?Q?_av_det_vanliga_mellanslagsbefriade=2c_eller_mellanslagsl?=
=?UTF-8?Q?=c3=b6sa=2c_namnet_som_b=c3=b6r_bli_en_l=c3=a5ng_harang_p?=
=?UTF-8?Q?=c3=a5_flera_MIME-rader.odt?="
Although it's a ugly file name it should be a valid header as far as i understand. I've tried a couple of email validators and they all agree this is a valid header. Why does Zend throw this exception and how can I prevent it?
The code that causes the crash
$oMail = new Zend_Mail_Storage_Imap($aImapSettings);
foreach ($oMail as $iMessageNum => $oMessage) {
if ($oMessage->isMultipart()) {
// Multipart messages
foreach (new RecursiveIteratorIterator($oMessage) as $oPart) { // <--crash
}
}
}
Stack trace
[07-Apr-2016 10:40:12 Europe/Stockholm] PHP Fatal error: Uncaught exception 'Zend_Mail_Exception' with message 'Invalid header value detected' in /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Header/HeaderValue.php:133
Stack trace:
#0 /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Part.php(600): Zend_Mail_Header_HeaderValue::assertValid('application/vnd...')
#1 /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Part.php(151): Zend_Mail_Part->_validateHeaders(Array)
#2 /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Part.php(289): Zend_Mail_Part->__construct(Array)
#3 /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Part.php(353): Zend_Mail_Part->_cacheContent()
#4 /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Part.php(578): Zend_Mail_Part->countParts()
#5 /www/zendsvr6/website/application/app/exterior/email/AppMailReceiver.php(509): Zend_Mail_Part->rewind()
#6 /www/zendsvr6/website/applic in /usr/local/zendsvr6/var/libraries/Zend_Framework_1/1.12.17/library/Zend/Mail/Header/HeaderValue.php on line 133
I also found this post suggesting that changing internal_encoding would help. It did not solve the problem in my case.
Not sure if this solution will fix your issue but I believe so:
https://github.com/zendframework/zf1/pull/567
go to your library/Zend/Http/Client.php file and apply following fix as mentioned in link above.
## -1592,6 +1592,11 ## protected function _validateHeaderValue($value, $recurse = true)
return;
}
+ // Cast integers and floats to strings for purposes of header representation.
+ if (is_int($value) || is_float($value)) {
+ $value = (string) $value;
+ }
+
if (! is_string($value) && (! is_object($value) || ! method_exists($value, '__toString'))) {

doctrine2: select error

I get the following fatal error while calling find method of entityRepository in a custom entityRepository class
Fatal error: Uncaught exception 'Doctrine\ORM\OptimisticLockException' with message 'Cannot obtain optimistic lock on unversioned entity Entities\Comment' in C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\OptimisticLockException.php:62 Stack trace: #0 C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\EntityRepository.php(140): Doctrine\ORM\OptimisticLockException::notVersioned('Entities\Commen...') #1 C:\Users\user\Desktop\projects\interview\application\models\Repositories\CommentRepository.php(24): Doctrine\ORM\EntityRepository->find('Entities\Commen...', 1) #2 C:\Users\user\Desktop\projects\interview\application\controllers\CommentController.php(65): Repositories\CommentRepository->activateByIds(Array) #3 [internal function]: CommentController->approveComments() #4 C:\Users\user\Desktop\projects\interview\system\core\CodeIgniter.php(359): call_user_func_array(Array, Array) #5 C:\Users\user\Desktop\projects\interview\index.php(203): require_once('C:\Users\user\D...') in C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\OptimisticLockException.php on line 62
Here is method in which i call find
public function activateByIds($arrayOfIds){
if (count($arrayOfIds)>=1) {
for ($i=0; $i<count($arrayOfIds); $i++){
$comment = parent::find('Entities\Comment', $arrayOfIds[$i]);
$comment->setIsactive(1);
$this->_em->merge($comment);
$this->_em->flush();
}
return true;
}
else return false;
}
What i'm doing wrong??
From what i read you have an OptimisticLockException
As said in this documentation:
An OptimisticLockException is thrown when a version check on an object
that uses optimistic locking through a version field fails.
You can find out more about Optimistic lock here
My guess is that their is a conflict with the $comment variable:
the first time you initialize $comment ($i=0) comment#1 is loaded
the second time (i=1, you find comment#2 but comment is already an entity and is manged) $comment =... tries to give comment#1 the values of comment#2 even the id that is uniq, so you are creating a conflict.
try this instead :
public function activateByIds($arrayOfIds){
$comments =array();
if (count($arrayOfIds)>=1) {
foreach($arrayOfIds as $i=>$id){
$comments [$i] = $this->getEntityManager()->find('Entities\Comment', $id); //new comment, not the old one!
$comments [$i]->setIsactive(1);
$this->_em->merge($comments[$i]);
$this->_em->flush();
}
return true;
}
else return false;
unset ($comments);
}
That way you are sure that you are not trying to re-use the previous comment instead of a new one.

Categories