PHP header() gives headers already sent

I am working on a checkout proces in Wordpress where if customer clicks on the checkout button he gets redirected to a payment provider.

Important to know:

  • I use a session in this proces.
  • I use PHP header() function to sent the customer to this location.

My problem: Now when you click the button, there is no redirect, but an error instead.

Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/website.com/httpdocs/wp-content/themes/template/header.php:24) in /var/www/vhosts/website.com/httpdocs/wp-content/themes/template/page-checkout.php on line 84

Line 84 is:

header( "Location: " . $payment-getPaymentUrl() );

So it looks like I need to do the redirect earlier, but I don't know how to do it. Has anyone any idea? Hook the init or send_headers action?

I have one solution at the moment which solves the problem, but I know that it is not the right one. The solution is placing ob_start() in the top of my header.php

Topic session headers init hooks Wordpress

Category Web


I had to do it with WordPress's inbuilt redirect function; wp_redirect();

wp_redirect( $payment->getPaymentUrl() );
exit;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.