Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to redirect after form submit

Maybe its a stupid question, but what is right way to redirect user to the success page after form is saved in database?

I dont know why, but if I add action="done.php", than the form does not save data to my database.

I tried to add header ("location:/done.php"); it worked, but when I moved page to original server ( PHP 4 and MySQL 3.23.5 ) there is error when I am trying to send the form Warning: Cannot modify header information - headers already sent by ........

Here is my php code :

if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$adress = $_POST['adress'];
$post = $_POST['post'];
$phone = $_POST['phone'];

$sql="INSERT INTO tekstile_users (id, name, email, company, adress, post, phone)
VALUES
('', '$name','$email','$company', '$adress', '$post', '$phone')";

if (mysql_query($sql,$con)) {

    header ("location:/done.php"); 
    }
    else {
echo "Something is wrong";
}

}//end of submit button

I fix it converting that .php file to UTF-8 without BOM .

Thanks all for suggestions!

like image 421
iKaspars Avatar asked Mar 03 '11 15:03

iKaspars


3 Answers

The "headers already sent" message means that your script has already output something. Is there anything displayed on the web page above this error message? Check for any whitespace before the <?php tag. Also check any include files for whitespace before or after <?php ?> tags.

The Location header should have a space after the ":" and should be a absolute URI, similar to the following:

header("Location: http://www.yoursite.com/done.php");
like image 150
qbert220 Avatar answered Sep 19 '22 02:09

qbert220


"Headers already sent" most likely means that there is some content in your .php file before your PHP code. This could be as simple as white space, or maybe your PHP code is embedded in HTML. In either case, make sure nothing comes before your PHP code, and you should be fine.

As for the correctness of this method of redirect, I believe it is a generally accepted technique.

like image 20
Ryan Kinal Avatar answered Sep 20 '22 02:09

Ryan Kinal


others have answered with respect to headers already sent. An alternative is to include or require done.php if the update was successful. Don't forget the exit after the include / require.

if (mysql_query($sql,$con)) {

    header ("location:/done.php");
    require_once('done.php');
    exit();
    }
    else {
echo "Something is wrong";
}
like image 35
Scott Avatar answered Sep 19 '22 02:09

Scott