Friday, August 17, 2018

PHP Header redirect not working




include('header.php');

$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
$MyDB->run();

header('Location:index.php');
exit;


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?



EDIT




header.php code:



include('class.user.php');
include('class.Connection.php');

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

?>




Test




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:




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...