PhP Headers and output buffering - php

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;

Related

header location unable to redirect

Overview:
I am having a block of code where I am checking for a condition and redirect to a page(manage_contents.php) if the condition(mysqli_num_rows($pages_set)>0) satisfies and thus everything after the if condition should not execute as the header has been redirected.
if(mysqli_num_rows($pages_set)>0) {
$_SESSION["message"] = "can't delete a subject with pages";
redirect_to("manage_contents.php?subject={$current_subject["id"]}");
}
$id = $current_subject["id"];
//Standard delete query
$query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
$result = mysqli_query($connection,$query);
if($result && mysqli_affected_rows($connection)==1) {
$_SESSION["message"] = "Subjects deleted";
redirect_to("manage_contents.php");
}else{
$_SESSION["message"]="Subject deletion failed";
redirect_to("manage_contents.php?subject={$id}");
}
But if I execute the above the code isn't redirecting(even if the if condition satisfied) and executing whatever is next to the if loop.
redirect_to function:
function redirect_to($new_location) {
header("Location:".$new_location);
}
Working solution for me:
if(mysqli_num_rows($pages_set)>0) {
$_SESSION["message"] = "can't delete a subject with pages";
redirect_to("manage_contents.php?subject={$current_subject["id"]}");
} else {
$id = $current_subject["id"];
//Standard delete query
$query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
$result = mysqli_query($connection,$query);
if($result && mysqli_affected_rows($connection)==1) {
$_SESSION["message"] = "Subjects deleted";
redirect_to("manage_contents.php");
}else{
$_SESSION["message"]="Subject deletion failed";
redirect_to("manage_contents.php?subject={$id}");
}
}
So,if i put all the code inside of the else statement then ofcourse it doesn't go to the else section when the if condition satisfies and hence works just fine.
Doubt:
Why the header doesn't redirect if I just leave the code outside of else section and why does it redirect just fine when the code is inside of else block?
I think both the code should work exactly same as far I know about header redirects.(when header is redirected all the following codes execution should skip).
Setting the Location header is not going to stop processing of the current PHP page. You'll need to explicitly exit:
function redirect_to($new_location)
{
header("Location: $new_location");
exit;
}
In other languages/frameworks (ASP.NET's Response.Redirect comes to mind) the current page's execution is stopped for you, but this does not happen in PHP and nothing in the documentation for header indicates otherwise.
Take a look to the caveat in http://php.net/manual/en/function.header.php : when you use the "Location" header you must take care that the code below it will not be executed (and your second code comply with it).

php message using sessions

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']="";

why ignores the header() function the result of my method?

$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);

How to redirect with header location in php when using ob_start?

<?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).

PHP cookie code causing chaos

My script is fairly simple. When someone tries to login, PHP checks the form data against a MySQL database, set's a cookie for the session, and refreshes the page. Now, I've pinpointed the cookie script to be causing chaos and completely stopping the thing from working. However, I don't know why. The code I am using is this:
<?php
header('Content-type: text/javascript');
$erroron="false";
$id='false';
$con = mysql_connect("localhost","***","***");
if (!$con)
{
die('$("#connecterror").stop().hide().fadeIn(); ');
}
mysql_select_db("***", $con);
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
if( $row['username']==$_POST["user"]&&$row['password']==$_POST["pass"])
{
if($row['confirmed']==1){
$id=$row['id'];
}
else{
echo '$("#erroractivate").stop(false,true).hide().fadeIn(200);';
}
}
else if( $row['email']==$_POST["user"]&&$row['password']==$_POST["pass"])
{
if($row['confirmed']==1){
$id=$row['id'];
}
else{
echo '$("#erroractivate").stop(false,true).hide().fadeIn(200);';
}
}
else{
if($erroron=="false"){
$erroron="true";
echo '$("#error").stop(false,true).hide().fadeIn(200);';
}
}
}
if($id=='false'){
echo '$("#error").stop(false,true).hide().fadeIn(200);';
}
else{
echo '$("#page").text("You have logged in, redirecting...");$("body").css("cursor","wait");setTimeout("location.reload(true);",2000);';
setcookie("sessionid", $id,0,'/','profile.campatet.com',false,true);
}
mysql_close($con);
?>
Now, this the the part that is not working:
setcookie("sessionid", $id,0,'/','profile.campatet.com',false,true);
If I take that off, the script successfully refreshes the page, but because there is no cookie set, you can't login. If I keep it on, it simply does nothing.
PHP's setcookie does it's thing via the headers, and unless you use output buffering, echoing before attempting setcookie will send the headers prematurely and prevent the cookie from being set.
http://php.net/manual/en/function.setcookie.php
http://www.php.net/manual/en/intro.outcontrol.php
The problem is that you cannot set a cookie after data has been sent to the browser. If you echo text and then try to set the cookie, it won't work.
Try reversing the echo and the setcookie() and make sure that no text before it has been sent to the browser.

Categories