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
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()
work around method : use ob_start() at the top of the page
other method : Please omit any white space before starting <?php or after ?> in the page
and also use exit() just after header()
Try this
<?php
include 'connect.php';
$id = $_POST['id'];
$idea = mysql_real_escape_string($_POST['new_idea']);
if(!$_POST['submit']) {
$message = "Please fill out the form!";
header('Location: index.php?message='.$message); exit;
} else {
mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error());
$message = "Idea has been added!";
header('Location: index.php?message='.$message); exit;
}?>
Pass the error message to index.php and display it there.
Don't print your output before header(). Store your data into session or pass it through URL.
Try this will surely help you .
Related
Here is my code, not too sure why it doesn't work but it cannot be processed. I can process phpinfo() correctly.
<?php
include("tools.php");
$username = $_POST["uname"];
$email = $_POST["email"];
$pasword = $_POST["pword"];
if(isset($username) and isset($email) and isset($password)){
if(add_user_database($username, $email, $password) == TRUE){
echo "You've been added!!!";
header("location:login.php");
}else{
echo "<script>alert('Error has occurd please contact " .
"support or try again later');</script>";
header("location:register.php");
}
}else{
echo "<script>alert('Please fill in all forms');</script>";
header("location:register.php");
}
?>
From the php docs,
"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."
You shouldn't need the echo things there, if you really wanted those messages, you could set them as $_SESSION('statusMessage'); and then on the redirect page check if it is set, echo out something to show it, and set them to undefined.
Also, please please please make sure that input gets sanitised in add_user_database()!!
EDIT:
Helpful hints
In the check login script:
if(add_user_database()){
$_SESSION['addUserStatus'] = "Success, you have been added, woo!";
header("Location: someOtherPage.php");
}else{
$_SESSION['addUserStatus'] = "Error! Please contact support for assistance!");
header("Location: someOtherPage.php");
}
In the some other page:
if(isset($_SESSION['addUserStatus']){
echo "<script>showLoginMessage('" . $_SESSION['addUserStatus'] . "')</script>";
$_SESSION['addUserStatus'] = undefined;
}
Header already sent error
look at
http://php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is sent
I was trying to post data to my database using PHP PDO from a form with action.php as the action. However, I couldn't redirect back to index.php once the data has been posted successfully, unless I used ob_start() at the beginning of action.php. Here is my code:
<?php
ob_start();
include('dbconfig.php');
$id = $_POST['id'];
$name = $_POST['name'];
if(!$_POST['submit']) {
echo('Please fill out the form!');
header('Location: index.php');
} else {
// Some statement using PHP PDO here
echo ('Data has been submitted');
header('Location: index.php');
}?>
For all I know, ob_start() is used to turn on output buffering, so my question is:
Why do I have to use that?
Do I have to add ob_end_clean() at the end of the file?
I don't know what is the problem. After i click the button, it only the data into database but will not go to next php page. Help me find out what is problems. Thank you.
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
header('Location: mcreport.php');
if($AddMCResult)
echo "<script>alert('Record Added.');</script>";
}
//button
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"/>
Try this
<?php
if(isset($_POST['btnSubmit']))
{
$txtName=$_POST['txtName'];
$txtFrom=$_POST['txtFrom'];
$txtTo=$_POST['txtTo'];
$txtReason=$_POST['txtReason'];
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('$txtName','$txtFrom','$txtTo','$txtReason')";
$AddMCResult = mysql_query($AddMCQ,$link);
if($AddMCResult)
{
echo "<script language=\"JavaScript\">\n";
echo "alert('Record Added.');\n";
echo "window.location='mcreport.php'";
echo "</script>";
}
}
?>
Your "Problem" is the result in $AddMCResult
After your have use header('Location: mcreport.php');
Your Script redirect to the given url and the result in $AddMCResult is not given any more
So a quick and dirty solution could be
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
$_SESSION['AddMCResult'] = $AddMCResult;
header('Location: mcreport.php');
}
AND on mcreport.php
if(isset($_SESSION['AddMCResult']) && $AddMCResult)
echo "<script>alert('Record Added.');</script>";
...
But check, that session_start() was called on both files ...
Check Carefully Table Name and Passing Parameters - Through one to another page - see get and post method-
<?php
include 'config.php';
$submit="submit";
$page = $_SERVER['PHP_SELF'];
$sl_no=$_POST['sl-no'];
$f_name=$_POST['f_name'];
$l_name=$_POST['l_name'];
if($submit)
{
$sql = "INSERT INTO table_name(sl_no,f_name,l_name) values('$sl_no','$f_name','$l_name')";
$result = mysql_query($sql);
echo "Thank you! Information entered.\n";
}
else
{
echo "There Is Something Going Wrong While Insertion";
header('Location: error.php');
}
After your header put die() like
header('Location: mcreport.php');
die();
And better you use Absolute urls.Also you can use exit() instead of die().
what is the problem about this code?
it create session correctly but dont redirect me, there is no "echo" before "header".
if(isset($_POST['login'])){
include('../maincore/connect-db.php');
$username=$_POST['username'];
$password=$_POST['password'];
$result = mysql_query("SELECT * FROM supporter WHERE username='$username'")
or die(mysql_error());
$row = mysql_fetch_array($result);
$pass=$row['password'];
if($password==$pass && $password!=''){
$_SESSION['username']=$username;
$_SESSION['name']=$row['name'];
$_SESSION['family']=$row['family'];
$_SESSION['id']=$row['id'];
$_SESSION['type']=$row['type'];
header('location: works.php');
}else{
header('location: index.php');
}
}
If this is your real code, shouldn't you be using sha1 or some sort of irreversible hashing for your passwords? Just.. wondering..
Just tried your code, things are working fine on my end.. so you have to give us more info on your error logs
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message
The document headers should be send before the document content.
PHP executes at real time, when I request a page the page isn't evaluated and sent so when you write the documment starts to send teh documment and no more headers can be added to the transfer.
Your problem is than you echo something before the header.
Error examples:
<?php
session_start(); // Send the session id header.
echo "This is a rawr text"; // Print something to the document
header("location: index.php"); // And this line will throw a error cause you already writed in the document.
?>
Another error:
<?php
session_start();
?>
<body>
Inside of body
</body>
<?php
header("location: index.php"); // this will throw a error cause the text upside has been already sent.
?>
Solution:
Put your code (header() functions) before write in the document.
I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.