0

I am trying to change the page using php after I set a session variable. I am calling the function from this code

 echo "<a href='index.php?id=";

          echo $row['id'];
          echo "'><img src='images/pic_1.jpg'

The function is the called properly and the variable is set but the page never redirects

    <?php 
      function getID() {
echo $_GET['id'];
session_start();
header("Location: home.php");
$_SESSION['id'] = $_GET['id'];

}

  if (isset($_GET['id'])) {
    getID();
  }
            ?>
  

I have tried both using the exact url and the file name but none work. How do I get to have both the page redirect and the $_SESSION['id'] variable to work?

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
Jake
  • 1
  • 1
  • how about placing the $_SESSION["id"] before the header? – dvr Sep 11 '17 at 22:49
  • 1
    1. _"I am calling the function from this code"_. No. you're not calling _any_ function from that code. 2. You can't use the `header()`-function after you output anything. All `header()`-calls need to be before _any_ output (echo, print_r, var_dump, etc...). 3. You should add an `exit;` after your `header()`-call to stop PHP from continuing to parse the script. – M. Eriksson Sep 11 '17 at 22:49
  • Not enough debugging going on to prove that the session variable wasn't actually set. Relation to Javascript entirely unclear. Unless proven otherwise; that's too likely the common headers-already-sent issue. – mario Sep 11 '17 at 22:53

2 Answers2

2

Response headers have to be sent before the response body in HTTP. Your code contains an echo statement (which starts sending the body) before the call to header(), so sending headers cannot work.

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
0

It is most likely due to you echo'ing something before you tell it to redirect. The header() function requires that it is run before you send any data to the client. In your case, you are echo'ing the ID before that. In your PHP log it will probably tell you that you attempted to send a header after other data.

If you want to make a transition page, for example, "Redirecting to blah blah blah", then you need to use an HTML redirect:

<meta http-equiv="refresh" content="1; url=/home.php" />

The 1 in the tag means to redirect after 1 second delay

Vilsol
  • 722
  • 1
  • 7
  • 17