Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php header() function won't redirect

I'm trying to post data from a form with insert.php as the action. However, I cannot redirect back to the index.php once the data has posted to the database.

I've searched through the following sites to find the answer:

    Trip Wire Magazine
    Daniweb

as well as ten stackoverflow questions on the subject.

Here is the code for the insert.php file:

<?php 
include 'connect.php';
$id = $_POST['id']; 
$idea = mysql_real_escape_string($_POST['new_idea']); 

if(!$_POST['submit']) {
    echo "Please fill out the form!"; 
    header('Location: index.php'); 
} else {
    mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error()); 
    echo "Idea has been added!"; 
    header('Location: index.php'); 
}?> 

From what I've gathered, the header() function won't execute if there's text output before it. I've tried this function without the echo "Idea has been added!"; and echo "Please fill out the form!";, but I still don't get a redirect.

Thanks in advance for your advice.

-MF

like image 217
Michael F Avatar asked Feb 04 '26 10:02

Michael F


1 Answers

From PHP documentation :

header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

And in your case, you are using echo before header()

like image 69
Nirav Ranpara Avatar answered Feb 07 '26 02:02

Nirav Ranpara