$result = $mail->send($recipient, $headers, $html);
if($result === 1)
{
$report= "1";
header("Location: objednavka.php?reaction=".$report);
//echo("Your message has been sent!");
}
else
{
$report= "2";
header("Location: objednavka.php?reaction=".$report);
//echo("Your message was not sent: " . $result);
}
if this mail function runs down the if statement decide that if it was successfull or not. If I use the echo() part it writes that Your message has been sent. But if I want to redirect the user to another page it doesnt work. Why? How can I call the header function successfully?
From PHP - header():
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.
You forgot to set a corresponding status code (header())
header("Location: objednavka.php?reaction=$report", true, 301);
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 am try to develop flash message using sessions in php
suppose on successfully delete query I am setting
$_SESSION["msg"]="record deleted successfully";
header("location:index.php");
and I have the following script on all pages which checks if msg variable is available it echo its value as below
if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
{
$msg=$_SESSION["msg"];
echo "<div class='msgbox'>".$msg."</div>";
unset($_SESSION['msg']); //I have issue with this line.
}
if I comment
unset($_SESSION['msg']);
message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.
You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.
Try adding exit; after header("location:index.php");.
Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1
In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
But this code probably will work as you want. Note that I have added exit after header line.
You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.
Another problem might be that you are doing more than one redirect.
You can simply set your session empty or null instead of unset it. Just do:
$_SESSION['msg']=NULL;
Or
$_SESSION['msg']="";
Here is a piece of code in PHP written in a separate file called core.php and this is included in register.php
if(($retuserkey = $this->dbcontroller->dbregister($email, $contact)) > 0){
//if user was successfuly registered send an email where he can activate his account!
$this->mailer->sendForReg($email,$hash,$flname);
echo "<script>alert('An activation link is sent to your email id. Please check you spam folder too. Please follow the link to complete the registration.'); window.location = './registersuccess.php';</script>";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=http://www.websiteaddress.com/registersuccess.php">';
$url = "http://www.websiteaddress.com/registersuccess.php";
if(!headers_sent()) {
//If headers not sent yet... then do php redirect
header('Location: '.$url);
exit;
} else {
//If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
}
mail("emailaddress#gmail.com","Registration $retuserkey",$email,"Subject");
}
Emails are sent both before and after the redirect. Both the emails are received but the redirect fails.
What am I doing wrong?
header() must be called before any actual output is sent and you have echo before it.
You can't do:
header('Location: '.$url);
exit;
after something has already been echo'd out: http://php.net/manual/en/function.header.php.
If you move your echo statements so they only print when the redirect isn't happening, then you should be OK.
header('Location: http://localhost/yourFileName.php');
exit;
header() function is used /* Redirect to a different page in the current directory that was requested */
header() function sends a raw HTTP header to a client
N.B: use right url
So... if you have a script that states something like so...
while($result = mysql_fetch_array($resource))
{
if($result['TITLE'] == $this->title)
{
header("LOCATION: profile.php?error=11");
}
echo 'testing';
}
//Create the database profile
$second_query = "INSERT INTO profiles(USER_ID, KEYWORDS, TITLE, INTRO) ";
$second_query .= "VALUES(".$this->userId.",'".serialize($this->keywords)."','".$this->title."','".$this->intro."')";
echo $second_query;
if($result = mysql_query($second_query))
{
if(isset($file))
{
$this->update_profile($this->files);
}
return true;
}else
{
return false;
}
and the first condition fails and sends the header back... If you don't return false after sending the header, does it continue running the script? I had an issue to where if the title was found in my database it would return the error, but it would continue running that script, thus inserting a duplicate title entry into my database.
So again... does a script continue executing even after you send a header? aka (in this case) a redirect?
If a location header is sent without an exit yes it continues to run script.
Valid:
header("Location: profile.php?error=11");
die(); // or exit();
Think about that header isn't executed by the PHP itself, it's executed by the browser, same thing when you apply a header("Content-Type: application/force-download"); it tells the browser that the following outputted block has to be downloaded.
So even if you set the header to another location, all code inside script, unless we exit, gets processed by PHP and then the browser gets the location and redirects.
Yes it will ,so exit your script after sending header
header("Location: profile.php?error=11");
exit;
<?php
ob_start();
echo "<body><p>Hello "
if ($condition) {
header( "Location: http://www.google.com/" );
exit;
}
echo " World!</p></body>";
ob_end_flush();
?>
When $condition is true I get this:
<body>Hello
What I want is when $condition will be true then go to Google!!!
I don't know what is happening, can you explain or give me a solution!?
Thanks.
Just add ob_end_clean(); before the header call.
Everything should work, just put an ; after echo "<body><p>Hello" and you will be fine..
If I were you, I would have started what might go wrong first then do the processing.
An example
$exit_condition_1 = some_value1;
$exit_condition_2 = some_value2;
if($exit_condition_1 == false){
//Redirect
//Exit
}
if(!$exit_condition_2){
//Redirect
//Exit
}
//start the buffer ob_start()
//show some HTML
//flash the buffer ob_end_clean()
there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.
An example: lets say that you want to view a product's info and you have a function that will do that
function view_product($product_id){
if(!$product = getProductById($product_id)){
//product does not exist, redirect
}
if(the user does not have enough access rights){
//show a message maybe
//redirect
}
//everything is alright then show the product info
}
To resolve a similar situation where a function was using ob_start() and there was header("Location: http://www.example.com"); after that but erring "already sent...", I replaced the header(... call with
echo "<script> window.location.href = 'https://www.example.com' </script>"
and it worked in that particular case (all that was needed was a just page redirect anyway).