Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP header redirection not working [duplicate]

I have done my research - and have found multiple solutions to this question, but for whatever reason mine is still not working!

Using IIS to host the site locally redirection works fine, however when I place it on my web server the redirection doesn't work.

Below is a segment of the code from my 'myaccount.php' page.

<?php
session_start();
if ($_SESSION['LoggedIn'] == true)
{    
    // ... Display page... lots of code here
}
else
// Session not active.
{
    // Redirect to login page.
    header("Location: http://{$_SERVER['HTTP_HOST']}/2ndassign/login.php");
}
?>

When that page is hosted online I am simply presented with a blank 'myaccount.php'... no redirection takes place. There is no whitespace present which should cause it to have an error.

So, I've cut my code down to this, so that it's as bare and simple as possible. Error reporting is on so it no longer presents a blank page, but spits out any errors.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
header("Location:http://{$_SERVER['HTTP_HOST']}/2ndassign/login.php");
?>

You can view the site at www.candlesoft.com.au/2ndassign/myaccount.php This might help you in helping me - to see what errors are being spat out.

My guts tell me it's a setting with my hosting provider.

CODE ON PASTEBIN - This is myaccount.php from www.candlesoft.com.au/2ndassign/myaccount.php - It is not an excerpt it is the entire file. (Shows whitespace isn't causing the error) http://pastebin.com/FUHPpT5A


Turns out the fault was that I needed to save the file as UTF-8 (without BOM)... PHP appears to interpret certain characters that BOM generates as whitespace - better explained here: How to fix "Headers already sent" error in PHP Thanks to Billy2mates for the link!

like image 457
user2388486 Avatar asked Feb 16 '23 12:02

user2388486


2 Answers

The error describes the issue

Warning: Cannot modify header information - headers already sent by (output started at   /home/candleso/public_html/2ndassign/myaccount.php:1) in /home/candleso/public_html/2ndassign/myaccount.php on line 4

Something is being sent to the browser therefore php can not redirect - even a white space or blank line will cause this issue. Header must be one of the first things sent to the browser.

like image 106
Eddie Jaoude Avatar answered Feb 23 '23 00:02

Eddie Jaoude


Try ob_start(); and ob_flush();

<?php
ob_start(); 
error_reporting(E_ALL);
ini_set('display_errors', 'On');
header("Location:http://{$_SERVER['HTTP_HOST']}/2ndassign/login.php");
ob_flush();
?>

This will work

like image 35
Jerin K Alexander Avatar answered Feb 22 '23 23:02

Jerin K Alexander