0

I'm trying to do a PHP redirect after my content has executed, however I cannot get the code to execute.

If I load this up, it redirects the page but doesn't insert anything to the database. If I comment out the header redirect line, it enters the data into my database.

How can I get the PHP to run and execute, and then redirect the page?

<?php require("gplus.php"); ?>
<?php require("database.php");?>    
<?php if(isset($personMarkup)): ?>
<?php
$checkuser = "SELECT gid FROM user WHERE gid = '$id'";
$updateuser = "UPDATE user SET name = '$name', pic = '$img' WHERE gid = '$id'";
$adduser = "INSERT INTO user (gid, name, pic) VALUES ('$id','$name','$img')";
$checkuserrlt = mysqli_query($con, $checkuser); 


if(mysqli_num_rows($checkuserrlt) > 0) {
   $result = mysqli_query($con, $updateuser) or die(mysqli_error());
} else {
     $result = mysqli_query($con, $adduser) or die(mysqli_error());
}
?>
<?php endif ?>

<?
mysqli_close($con);
?>
<?php
header( 'Location: http://google.com' );
exit();
?>
K20GH
  • 6,032
  • 20
  • 78
  • 118
  • 3
    Side note: you don't need 90% of your `` tags – jterry Jun 20 '13 at 12:19
  • Yes. If I comment out the header line then it executes fine. @jterry - Yep, just trying to get this working before I tidy up. Did a merge of content. – K20GH Jun 20 '13 at 12:19
  • The code is good, but remember if you're going to use html, you must send the headers before the html starts. – Orel Biton Jun 20 '13 at 12:22

1 Answers1

5

When you do:

<?php endif ?>

<?

You are outputting content in your browser, in that case, a new line. When you do that, PHP will send the HTTP headers back to the client, and it becomes impossible to add new headers. That's why your header() function won't work.

Open and close your PHP tags once. <?php at the beginning of your script, ?> at the end. Also you should see error messages, make sure they are enabled (in development only, you don't want to show error messages in production):

error_reporting(-1);
ini_set('display_errors', -1);

If you had error reporting enabled, you would certainly see this error message:

Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23

You can read more about this error here: How to fix "Headers already sent" error in PHP

Community
  • 1
  • 1
Tchoupi
  • 14,560
  • 5
  • 37
  • 71