PHP Header redirect not working




$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];

$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query


The above code keeps giving me an issue with the redirect. The error is the following:

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php:15) in /Applications/MAMP/htdocs/testygubbins/OO/test/form.php on line 16.

I am totally flummoxed by this. Does anyone know what I should be doing to make it work?


header.php code:


$date = date('Y-m-j');

    <link rel=StyleSheet href="css/style.css" type="text/css" media=screen>
<div id="page">
12/20/2016 3:58:06 PM

Accepted Answer

Look carefully at your includes - perhaps you have a blank line after a closing ?> ?

This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.

Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.

(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).

Finally, as the PHP manual page for header points out, you should really use full URLs to redirect:

Note: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

1/8/2009 11:18:29 AM


1) There should be NO output (i.e. echo... or HTML parts) before the header(...); command.

2) After header(...); you must use exit();

3) Remove any white-space(or newline) before <?php and after ?> tags.

4) Check that php file (and also other .php files, that are included) - they should have UTF8 without BOM encoding (and not just UTF-8). Because default UTF8 adds invisible character in the start of file (called "BOM"), so you should avoid that !!!!!!!!!!!

5) Use 301 or 302 reference:

header("location:",  true,  301 );  exit;

6) Turn on error reporting. And tell the error.

7) If none of above helps, use JAVASCRIPT redirection (however, discouraged method), may be the last chance in custom cases...:

echo "<script type='text/javascript'>'';</script>"; exit;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow