Function of header () function in PHP [duplicate]

0

I'm using the following code:

if (!$lRet):
    // Volta para o cartão eletrônico.
    header('Location: '.$_SESSION['CFG_DIR_ROOT'].'index.php');
endif;

In this way it simply does not work and continues to run the script, but if we include a line of code below header () it works.

if (!$lRet):
    // Volta para o cartão eletrônico.
    header('Location: '.$_SESSION['CFG_DIR_ROOT'].'index.php');
    die();
endif;

This works, that is, it goes to index.php and does not execute die (). If I replace die () [exit () also works] with another echo type or $ a = 'b', etc., it also does not work.

What's the magic?

Today I will try to run on another server, this time Linux, to see if I have different operation or some error message. Then put the result here.

    
asked by anonymous 17.10.2015 / 05:17

4 answers

-2

Have you tried using the ob_start at the beginning of the code to clear the buffer?

Whenever this happened to me, I used this function, which solved the problem, I hope it helps you too!

    
17.10.2015 / 05:57
2

The function header() basically serves to send HTTP headers.

Normally functions that change or send HTTP headers should be called before any other data output by the script.

Some of these functions are:

  • header / header_remove
  • session_start / session_regenerate_id
  • setcookie / setrawcookie

See:

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

This call returns error, because something has been printed before the request has been made. Literally, nothing can be printed before a header has been defined, this includes the white spaces before and after the php tag, special characters, etc.

Another thing to keep in mind is that once we define a header nothing else can be executed, so we use exit, die to make sure nothing else is executed after this line.

Some References:

17.10.2015 / 06:50
1

Your header request is probably found after some HTML, so some output has already been sent to the browser. Headers can only be sent before any HTML output.

So, a ob_start() will get all the output data and buffer. The data will only be sent to the browser at the time the buffer is closed.

session_start(); // 1ª linha do arquivo
ob_start(); // 2ª linha do arquivo
// ...
// ...
// ...
if (!$lRet):
// Volta para o cartão eletrônico.
header('Location: '.$_SESSION['CFG_DIR_ROOT'].'index.php');
endif;
// ...
// ...
// ...
    
17.10.2015 / 14:24
0

Try this:

if(!isset($lRet)){
    // Volta para o cartão eletrônico.
    header('Location: '.$_SESSION['CFG_DIR_ROOT'].'index.php');
}

Always remember to put session_start() in the first line of the code.

    
17.10.2015 / 06:16