php message using sessions - php

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

Related

Redirect page after delete account in php

I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help

PHP Unable to handle request

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

Unsetting PHP session variable doesnt display error message

I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.
I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...
This is part of my code flow...
<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
header('Location: index.php');
}
.
.
//in html body
<?php
if (isset($_SESSION['user_found'])){
if($_SESSION['user_found'] == 0){
?>
<div>
<p class = "bg-danger text-danger">Username Password Mismatch</p>
</div>
<?php
unset($_SESSION['user_found']);
}
}
?>
Now, if unset is removed..it works fine. If it is there, there is no display of error message.
Try not reloading the same page.. remove the header redirect.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
//header('Location: index.php');
}
When I tried the your code, things seem to work fine. Something should be wrong with the code you've not mentioned here..
To troubleshoot the problem instead of
unset($_SESSION['user_found']);
try changing the value of the variable.. say
$_SESSION['user_found'] = -1;

why i cant redirect to another page

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.

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

Categories