My recent log have a lot of this error (every page not found create one error):

RuntimeException: Failed to start the session because headers have already been sent by "mysite.com/public_html/vendor/symfony/http-foundation/Response.php" at line 1276. in Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start() (line 141 of mysite.com/public_html/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php) #0 mysite.com/public_html/core/lib/Drupal/Core/Session/SessionManager.php(164): Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start() #1 mysite.com/public_html/core/lib/Drupal/Core/Session/SessionManager.php(195): Drupal\Core\Session\SessionManager->startNow() #2 mysite.com/public_html/vendor/symfony/http-foundation/Session/Session.php(193): Drupal\Core\Session\SessionManager->save() #3 mysite.com/public_html/core/lib/Drupal/Core/StackMiddleware/Session.php(60): Symfony\Component\HttpFoundation\Session\Session->save() #4 mysite.com/public_html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #5 mysite.com/public_html/core/modules/page_cache/src/StackMiddleware/PageCache.php(184): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #6 mysite.com/public_html/core/modules/page_cache/src/StackMiddleware/PageCache.php(121): Drupal\page_cache\StackMiddleware\PageCache->fetch(Object(Symfony\Component\HttpFoundation\Request), 1, true) #7 mysite.com/public_html/core/modules/page_cache/src/StackMiddleware/PageCache.php(75): Drupal\page_cache\StackMiddleware\PageCache->lookup(Object(Symfony\Component\HttpFoundation\Request), 1, true) #8 mysite.com/public_html/core/modules/ban/src/BanMiddleware.php(50): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #9 mysite.com/public_html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\ban\BanMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #10 mysite.com/public_html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #11 mysite.com/public_html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #12 mysite.com/public_html/core/lib/Drupal/Core/DrupalKernel.php(664): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #13 mysite.com/public_html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request)) #14 {main}.

Site still running good but this error keep flood my log.

CommentFileSizeAuthor
#3 headers_already_sent-2852657-3.patch478 bytesguncha25

Issue fork drupal-2852657

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

tran_tien created an issue. See original summary.

ksavoie’s picture

I am experiencing this same behavior.

D8: 8.2.6
SOLR: 6.4.1
Search404: 8.x-1.0-beta2

guncha25’s picture

StatusFileSize
new478 bytes
guncha25’s picture

Status: Active » Needs review
tran_tien’s picture

Patch #3 work.

Edited : Not work, every 404search redirect to homepage.

tran_tien’s picture

Ooop! Sorry. Patch #3 make module stop working, every 404search redirect to homepage.

tran_tien’s picture

Status: Needs review » Needs work
pradeeshrajd’s picture

Status: Needs work » Postponed (maintainer needs more info)

Cant reproduce this in Drupal version 8.4. Need more info

tran_tien’s picture

Version: 8.x-1.x-dev » 8.x-1.0-beta2
Status: Postponed (maintainer needs more info) » Active

What infomation do you need?

This error keep filling up my watchdog and make my sqlserver down.

tran_tien’s picture

Project: Search 404 » Drupal core
Version: 8.x-1.0-beta2 » 8.5.3
Component: Code » other
Priority: Major » Normal
Issue summary: View changes

When i uninstall Search 404, error still here, so i moved this bug to Drupal core.

cilefen’s picture

Are the exceptions occuring now the same?

shawngo’s picture

I was getting the same (or very similar) error. Checking the "Disable error message" setting in Search 404 Settings (admin/config/search/search404) worked for me.

tran_tien’s picture

Status: Active » Closed (works as designed)

Go to Basic site settings : /admin/config/system/site-information

Clear Default 404 (not found) page value.

Fixed.

socialnicheguru’s picture

Status: Closed (works as designed) » Needs work
Related issues: +#2957019: Failed to start the session because headers have already been sent

Isn't this more of a work around than a fix?

Possible cause outlined in this issue: https://www.drupal.org/project/flag/issues/2957019#comment-12622082:

I spent two hours walking through the bootstrap with a debugger, and that does not appear to be the case. The HTTPKernel starts the session of it's own accord before Session::set() is ever called. Calling ::set() after the session has started is fine because it's ::save() that does the actual persisting to $_SESSION.

I think the problem is we're setting $_SESSION directly, and on some PHP configurations that causes a session auto-start that confuses the hell out of the middleware and creates this error.

cytherion’s picture

Just in case it's been overlooked as a potential cause: Including the ?> closing PHP tag in your module's php files (.module and .php includes) can cause this error. See: https://www.drupal.org/docs/develop/standards/coding-standards#phptags

walii’s picture

Please try this https://stackoverflow.com/questions/6249707/check-if-php-session-has-alr...

if (session_status() == PHP_SESSION_NONE) {
  $_SESSION['flag'] = TRUE;
  $this->sessionManager->start();
}
rathod03’s picture

Hi,
I am also suffering from the same problem and after more debug I have found the solution. There is a blank line in my index.php file before then <?php tag when I removed those blank lines the error is fixed. Please have a look your .php files. And if anyone has the same remove them and look what happened. Thanks

mister vandenweb’s picture

Hello,

Do some of you use external cache systems such as Varnish, memcached or Cloudflare ?

EurekaWeb’s picture

Druide Vandenweb CreditAttribution: Druide Vandenweb as a volunteer commented about a month ago
Hello,

Do some of you use external cache systems such as Varnish, memcached or Cloudflare ?

Yes using cloudflare. And this issue is only occurring when anonymous users triggers the search 404.

Clearing the Drupal default 404 as suggested in #13 cleared the PHP issue however, custom path for search 404 is not working.

krrishnajee’s picture

I had the same issue, But in my case it's causes by the following RedirectResponse redirection.

$response = new RedirectResponse($path);
$response->send();
return;

Changing above code into following is fixed my issue.
return $response = new RedirectResponse($path);

c.e.a’s picture

does anyone been able to provide a patch to fix this issue!

I am suffering as well from it, and noticing plenty of issues created concerning this issue on different contrib modules such as:

For me, this is happening when for Authenticated users including the administrator (user/1) user and not for anonymous users like mentioned in #19

#13 does indeed fix the issue, but I believe this is not a proper way to fix an issue by removing another feature from drupal core such as: Clear Default 404 (not found) page value

#18 Yes, I am using Cloudflare and the entire website does not have a cache system even the built-in cache system is disabled as per project requirements.

Drupal Version: 8.6.10
PHP: 7.1.11

c.e.a’s picture

Any update on this issue... Thank you

aposudevsky’s picture

I had exactly the same problem, my logs was filling up with this message.
The issue for me was when anonymous user (for the first time) visits the page that is unpublished. User should see unauthorized page, but I found out that this page didn't existed anymore. After I fixed that in the Basic Site Settings the error haven't appear anymore.

Kirti Garg’s picture

I faced this problem while downloading pdf from controller route. Removing cache for this route worked in my case.

return ['#cache' => ['max-age' => 0]];

greggles’s picture

Version: 8.5.3 » 8.8.x-dev
Issue summary: View changes
Status: Needs work » Active

Moving this to version 8.8.x as I just ran into it there. Also setting status to "Active" because the patch here was for a different module.

rymcveigh’s picture

I ran into this issue as well. In my case, the error was seen in two different redirects. The first was a redirect I implemented in a custom hook_user_login The error showed up when I used a new RedirectResponse($url); to implement the redirect like this:

$response = new RedirectResponse($url);
$response->send();

I then experimented with using a hook_form_FORM_ID_alter on the user form with a redirect in the form submit function but the error persisted.

I was able to resolve the error by "killing" the page cache using \Drupal::service('page_cache_kill_switch')->trigger(); after the send:

$response = new RedirectResponse($url);
$response->send();
 \Drupal::service('page_cache_kill_switch')->trigger();

In a second instance where I was using a new RedirectResponse($url); within an event subscriber I was able to resolve the error by switching the $response->send(); to $event->setResponse(new RedirectResponse($url)); and killing the cache:

$event->setResponse(new RedirectResponse($url));
\Drupal::service('page_cache_kill_switch')->trigger();
handkerchief’s picture

I have the same issue with a REST export view... My requests are blocked with this error message.

handkerchief’s picture

What is the best practice to debug this error?

reloxo95’s picture

I had the same issue with a custom page and custom PDF generation. I only could generate once the PDF, then I received an error of RuntimeException.
After read a lot a realised that could be the cache and I desactivated to my custom view and works fine! I dont know if this could help but in my case works

vishaljd’s picture

I was getting the same issue shown above while using the RedirectResponse . But i have a solution for that please try this solution hope that will works for you.

use Symfony\Component\HttpFoundation\RedirectResponse;

$response = new RedirectResponse($path);
$response->send();
exit; // simple add exit in the replacement of return keyword that's it.

It worked for me.

realgt’s picture

@vishaljd that exit; worked for me, thank you!

AmandeepKaur’s picture

Issue tags: +VB_Drupal_Contrib_Aug
cilefen’s picture

Status: Active » Closed (works as designed)

It looks like this was co-opted from a search404 issue and the remaining comments are about API usage.

AmandeepKaur’s picture

Issue tags: -VB_Drupal_Contrib_Aug
iaugur’s picture

I was getting this error when redirecting a view with only one result using RedirectResponse.
#30 - adding exit; worked for me - thanks vishaljd!! ;)

khoa pham’s picture

thanks Kirti Garg a lot.
#24 worked for me

brianwagner’s picture

#26 worked for me. Problem only occurred with anonymous users using a RedirectResponse in event subscriber.

c.e.a’s picture

Working Solution:

// Redirect the user.
$response = new RedirectResponse("/user/login");
return $response; // When using $response->send(); messages are not displayed for anonymous users.
\Drupal::service('page_cache_kill_switch')->trigger();
// 'Kill page cache' or add 'exit;' at the end to prevent: "Failed to start the session..." @See: #2852657
chrisdarke’s picture

quick question, I am not sure how that third line of code is ever executed, after the return statement?

John Stott’s picture

I had this issue, but returning the response alone did not perform the redirect, this worked for me:

$redirect = new RedirectResponse($url);
$redirect->send();
return $redirect;
nikitas’s picture

I had the same problem issue #20 did the trick for me. I use this code in an eventSubscriber like this

<?php

namespace Drupal\pixelthis\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Url;
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Class ReportSubscriber.
 */
class ReportSubscriber implements EventSubscriberInterface {

  /**
   * Constructs a new ReportSubscriber object.
   */
  public function __construct() {
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['initReportWeekly'];
    return $events;
  }

  /**
   * This method is called when the init is dispatched.
   *
   * @param \Symfony\Component\EventDispatcher\Event $event
   *   The dispatched event.
   */
  public function initReportWeekly(Event $event) {

    $nextFridayData = manageNextFridayReport();
    //Make sure we can only have 1 report per Friday per user.
    if (isset($nextFridayData['nid']) && $nextFridayData['nid'] instanceof ContentEntityInterface) {
      $redirectUrl = Url::fromRoute('entity.node.edit_form', ['node' => $nextFridayData['nid']->id()]);
      return $response = new RedirectResponse($redirectUrl->toString());
    }
  }
}
manuel.adan’s picture

I ran into this after update to D9.2. Redirect after login module is also affected, some fix can be found at #3214949: Headers have already been sent after upgrade to Drupal 9.2 (can't login)

mohd.shadab’s picture

I was getting same error by using RedirectResponse in my hook_user_login after updating Drupal 9.2.0, I updated my code as per below and It worked for me.

//Old code

$response = new RedirectResponse($url);
$response->send();

//New code

\Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);
Simon_lemaitre’s picture

@mohd.shadab,

This last solution works for me !

Thanks a lot!

xld’s picture

@mohd.shabad,

Thank you!!!

lynettew’s picture

I ran into the RunTime Error, but it made reference to my custom .theme file.

Uncaught PHP Exception RuntimeException: "Failed to start the session because headers have already been sent by ".../docroot/themes/custom/airforce_theme/airforce_theme.theme" at line 1." at .../vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php line 150

https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-s... had some good info on headers (as I'm not an expert on them), so I read that and removed my .theme file in my custom theme folder (I didn't have anything in it, it was blank), and that seemed to fix my problem.

mordonez’s picture

@mohd.shabad,

Thanks!

miroslav-lee’s picture

@mohd.shabad, Thanks!

phannphong’s picture

Thanks @mohd.shadab. It works like a charm!

bhanojeerao’s picture

Thanks @mohd.shadab,

#43 worked for me after research!

karthikeyan gandhimathinathan’s picture

I was getting same error by using RedirectResponse in my hook_user_login after updating Drupal 9.2.7, I updated my code as per below and It worked for me.

//Old code

return (new RedirectResponse($redirect))->send();

//New code

return \Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $redirect);

jkdaza’s picture

I had a similar issue in hook_user_login()

When upgrading to Drupal 9.2.7 I have changed:

$response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
$response->send();

to:

\Drupal::service('request_stack')->getCurrentRequest()->query->set('destination', $url);

dongtian’s picture

Thanks @mohd.shadab,

The solution works for me !

ConradFlashback’s picture

#43 works
Thanks @mohd.shabad

ian-zabl’s picture

#43 Thanks so much @mohd.shabad!

Anonymous’s picture

#43 resolved my problem as well.
Thank you @mohd.shadab!

mark.estocapio made their first commit to this issue’s fork.

Anonymous’s picture

Thank you @mohd.shadab!

jacomo475’s picture

#46 Thank you so much @LynetteW, your heads up helped me resolve my issue.

Like you, I was using a custom theme. There was a file .theme with two empty lines in it.

I first tried deleting it, and it solved the problem immediately, no more RuntimeException. I could finally access the admin tools.

However, I noticed that now every admin panels was complaining that the .theme file was missing.

I restored the .theme file, but REMOVED ONE EMPTY LINE from ti, and that sorted everything!

Thanks again for your help, without you I'd be still stuck.

anybody’s picture

If using Search404, this issue is what you're looking for: #3087929: Failed to start the session because headers have already been sent