0

When submitting a form, I am receiving this warning:

Warning: Cannot modify header information - headers already sent by (output started at /home/domainname/public_html/test.php:4) in /home/basewars/domainname/test.php on line 19

I've had a look at How to fix "Headers already sent" error in PHP and I believe it is because I am echoing the <title>, however I cannot think of a way around this.

<!DOCTYPE html>
<html lang="en">
<head>
<?php
if(strpos($_SERVER["SCRIPT_NAME"], 'user') == true) {
   echo '<title>'.$username.' - Hello</title>';
}else{
   echo '<title>Hello</title>';
}
?>
</head>
<body>
<form method="post">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
   header('Location: login.php'); 
   exit();
}
?>
</body>
</html>
  • This is because you echo not only title, but even ` ` – u_mulder Jul 01 '17 at 10:04
  • Possible duplicate of [How to fix "Headers already sent" error in PHP](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – apokryfos Jul 01 '17 at 10:43

4 Answers4

2

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

http://php.net/manual/en/function.header.php

<?php
if(isset($_POST['submit'])) {
   header('Location: login.php'); 
   exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if(strpos($_SERVER["SCRIPT_NAME"], 'user') == true) {
   echo '<title>'.$username.' - Hello</title>';
}else{
   echo '<title>Hello</title>';
}
?>
</head>
<body>
<form method="post">
<input type="submit" name="submit">
</form>
</body>
</html>
Neodan
  • 5,154
  • 2
  • 27
  • 38
0

The headers have already been sent because the first line in the file is HTML. Outputting the !DOCTYPE tag, or anything else will cause the headers to be sent first. You need to do your test and header output before you send any data at all.

alzee
  • 1,393
  • 1
  • 10
  • 21
0

**Try this code for redirect** 
echo '<script>window.location.href ="'.Your url.'";</script>';
Jalin
  • 95
  • 7
0

You should use ob_start() at the top.

However, I'm not sure what are you trying to achieve? as your script does nothing.

MyLibary
  • 1,763
  • 10
  • 17