Jump to content

redirecting with headers never works


viperjts10

Recommended Posts

I've always never understood the use of headers. All I know is that it has to be the first thing output using php, and there must be no white space etc..

 

But how can that be if I use the header in an 'if' statement or whatnot. Here's what I'm trying to do...I'm using a simple 'if' statement to see if the user logged out:

 

		if($session->is_logged_in())
	{
		/* Kill session variables */
		$session->logout();
		//$_SESSION = array(); // reset session array
		redirect_to('index.php');
		//echo "<meta http-equiv=\"Refresh\" content=\"0;url=index.php\">";
	}

 

My redirect function is below:

 

	function redirect_to($location = NULL) {
	if ($location != NULL) 
	{
		header("Location: {$location}");
		exit;
	}
}

 

How can I possibly use a header without having any whitespace before hand if I need to test a condition first?

 

Link to comment
https://forums.phpfreaks.com/topic/207808-redirecting-with-headers-never-works/
Share on other sites

function redirect( $url ){
if (! headers_sent( ) ){

header( "Location: ".$url );
exit( 0 );
}
echo "<script language=Javascript>document.location.href='".$url."';</script>";
exit( 0 );
} 

redirect('http://wizecho.com'); //redirect to any url

Hi  viperjts10,

I ran your code and the redirection worked for me.

 

The only thing i added was a class to create the session object with methods is_logged_in() and logout() both of which returned true.

 

I'm not sure why you are having problems but it must be something in the code preceeding the snippets you posted.

 

The full code I used is below.

 

All the best,

Fergal

 

<?php

class session
{
    function is_logged_in()
    {
        return true;
    }
    
    function logout()
    {
        return true;
    }
}

$session = new session();

if($session->is_logged_in()) {
        /* Kill session variables */
        $session->logout();
        //$_SESSION = array(); // reset session array
        redirect_to('index.php');
        //echo "<meta http-equiv=\"Refresh\" content=\"0;url=index.php\">";
}

function redirect_to($location = NULL) {
    if ($location != NULL) 
    {
            header("Location: {$location}");
            exit;
    }
}

It's nothing to do with the server. When you send output to the browser (even white-space) the response headers (your redirects, cookies, etc.) are sent first. This means once output has been sent, you're unable to set anymore response headers.

 

I don't know if this is just from copying the code into the post, but I can see an empty line above your PHP tag. quite possibly this is the cause of your problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.