$_SESSION not working/ sending out wrong result in php - php

I am trying to navigate to a different page whenever a user clicks on a particular link [basically these are user links which navigate to user profile page when clicked].
My problem if I store the SESSION variable and display it in the same page as the link, it echos out all the emails ids corresponding to that user, but as soon as I navigate to a different page,I can see SESSION displays the wrong result [some other email id].
Here is my code.
<?php echo $firstName.' '.$lastName;?>
This link is displayed as many times as there are records in the database.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>
Now if I just echo the email like above on this page itself, it displays all the emails corresponding to that user. Like this.
user1 : emailid1
user2 : emailid2
But as soon as I navigate to home.php, the SESSION variable always prints out the first email only.
home.php
session_start();
echo 'email id is '.$_SESSION['email'];
I know I am going wrong somewhere but any suggestions would be of great help.

Try with below code.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
session_start();
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>

Related

the webpage auto-submits with previous session variables after refresh

I have a webpage that allows users to submit a query and get result in email.The user selects values for three variables and the email address. My problem is that everytime I refresh the page the form resubmits itself with old values and send the email (i.e I am not even clicking on submit query). I tried using $_POST=array() but it is still not working.
Here is my code:
<?php
if(isset($_POST['submit'])){
$varApp= $_POST['App'];
$varConfig = $_POST['Config'];
$varCtrType = $_POST['CtrType'];
$varEmail = $_POST['mailid'];
exec("/py $varApp $varConfig $varCtrType 2>&1",$output );
if ($output[8] == "Empty"){
echo "<div style ='font:22px Arial,tahoma,sans-serif;color:#ff0000'><br>No Data Available! <br></div>";
}
else {
exec(' printf "Please find attached the query result for following selection:\n\nApp: '.$varApp.' \nConfig: '.$varConfig.' \nCounter Type: '.$varCtrType.' \n\n Thanks! " | /bin/mail -s "Database Query Result" -a '.$output[8].' '.$varEmail.' 2>&1', $output2 );
echo "<div style ='font: 18px Arial,tahoma,sans-serif;color:#10ac84'><br><b> Please check your email for result !<b> <br>";
echo '<script language="javascript">';
echo 'alert("Please check your email for result! Submitted Query details: Selected App: '.$varAPP.' Configuration:")';
echo '</script>';
}
$_POST=array();
}
?>
</body>
I have not given the html part here.
So, everytime a user refreshes the page he gets an email again with previous session query results.
Any guidance here is highly appreciated.
Note: I am not using mail or pHPmailer here but that is not what I need to discuss here.
Thanks,
Taken from this answer:
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.

Show text only for specific user in php

I am trying out simple PHP page. I am trying out the following:
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
echo ("<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><a href='/admin.php'>ADMIN</a> | <a href='/logout.php'>Logout</a></h1></span></p>");
?>
I want to show admin page (link) only for a particular user. Like admin should be hidden near loggout if admin user doesn't login...How do I do it?
I have got session's userID but I don't know how control the text in php/html.
Help on this will be great.
Thanks!
If session userId is this then show admin
The semantics of your statement are your exact code:
if ($_SESSION['username'] == 'admin') {
// output the admin stuff
}
(Or however you check if the user is an admin. Based on username, some identifier, something else, etc. Your question doesn't specify.)
So you'd output whatever is before the admin link, then conditionally output the admin link, then output whatever is after it. Something like this:
echo "<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'>";
if ($_SESSION['username'] == 'admin') {
echo "<a href='/admin.php'>ADMIN</a> | ";
}
echo "<a href='/logout.php'>Logout</a></h1></span></p>";
There are many other ways you can structure it as well. Perhaps store the resulting links in variables and conditionally concatenate them as needed, then echo the result of that only once at the end.
But the concept is the same however you do it. If the user is an admin, output the admin link. That way if the user is not an admin, they never see that link.
Note: The admin page itself must also implement security. There is nothing to stop a user from guessing the link and trying to open that page. Do not consider the approach in your question to be security. This is nothing more than user experience.
you need to store html links in your variables, and use them where needed, like this,
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
$adminLink = " <a href='/admin.php'>ADMIN</a> | ";
$logoutLink = " <a href='/logout.php'>Logout</a>";
?>
// suppose your html header link container
<div>
<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><?php echo $adminLink.$logoutLink ?>
</h1></span></p>
</div>
============================================
for blocking acces on admin page
<?php
// start session
session_start();
// check if username is admin
replace it with your admin user name
$adminUsername = "admin";
if($_SESSION['login_user'] !== $adminUsername){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
?>

PHP sessions and session destroy

I have created a page where 'Job's' stored on a database are deleted.
On a page called
delete.php
the job to be deleted is selected.
The user is then directed to deleteaction.php where the job is deleted.
The user is then auto redirected back to
delete.php
This all works fine however once the user is returned to delte.php I would like a pop-up/ alert saying 'Job deleted'.
However if the user enters the page not from
deleteaction.php
then I dont want this pop-up to appear. I have tried to use sessions where a variable
$status
indicates if the user has just been directed to
deleteaction.php
and a job has been deleted.
Code on deleteaction.php:
session_start();
$id=$_GET['id'];
$sql= "DELETE FROM `Job` WHERE `Job`.`Job_Customer_id`='". $id."';";
$stmt=$dbh->query($sql);
$status = "deleted";
$_SESSION['delstat'] = $status;
header("Location:delete.php");
Code from delete.php:
session_start();
$status = $_SESSION['delstat'];
if ($status = "deleted"){
echo '<script language="javascript">';
echo 'alert("Job Deleted")';
echo '</script>';
}
else {
echo "No";
}
session_destroy();
........
The problem is the page delete.php always displays the alert that a job has been deleted every time the page is visited.
Not sure if its something wrong with my loop or the session use?
Thanks in advance!
You're presently assigning = instead of comparing == in
if ($status = "deleted")
being always TRUE
change that to
if ($status == "deleted")

Redirect back to previous page with dynamic urls

Sorry for the newbie question but I can't figured it out.
When user login I store his data in sessions like this
$_SESSION['user_id'] = $res['user_id'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['level'] = $res['level'];
$_SESSION['firstname'] = $res['firstname'];
$_SESSION['lastname'] = $res['lastname'];
$_SESSION['user_image']= $res['user_image'];
$_SESSION['email'] = $res['email'];
header('Location: users/main.php');
On every page I've put session_start() and everything work just fine.
There are some pages like:
http://example.com/users/page.php?user_id=1
When user open page.php he see table filled with data from mysql with buttons edit/delete. When he click on edit button of item 1 is opened page which get if (isset($_GET['item_id'])){...
http://example.com/users/page.php?item_id=1
Now how to redirect user back to page.php?user_id=1 when he click button submit?
I've tried with this
header("Location: page.php?user_id=$user_id");
but it doesn't return since properly and URL become http://example.com/users/page.php?user_id=
$user_id is not defined, so first defined it.
instead of
header("Location: page.php?user_id=$user_id");
Use below code
$user_id=$_SESSION['user_id']l
header("Location: /page.php?user_id=$user_id");

Redirect on logout and display "You have successfully logged out!"

I have a membership service on my website. Currently when someone logs out they are redirected to logout.php that has this code on it:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!<br><a href = '/review-pratt/index.php' class='icon-button star'>Return Home</button></center>";
}
?>
Instead of having the users be taken to "logout.php" and viewing a boring page that says they logged out. I want them to be redirected to index.php. That part is easy, I know.
I am wanting a notification bar across the top to appear notifying them that they successfully logged out. I have tried to do this before and never got anything to work. Any help or suggestions would be appreciated!
Update
I have changed the logout.php code to:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//Redirect with success message
header('Location: /index.php?msg=' . urlencode("You have been successfully logged out!"));
}
?>
and added the following code to my index.php:
<?php
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
?>
And when I log out I receive this error:
Warning: Cannot modify header information - headers already sent by (output started at /home/content/38/10473938/html/review-pratt/business_profiles/logout.php:19) in /home/content/38/10473938/html/review-pratt/business_profiles/logout.php on line 35
you could do something like this:
header('location: index.php?status=loggedout');
and in your index.php file just look to see if status is not empty, and show a div with the status like this:
<?php
if(!empty($_GET['status'])){
echo '<div>You have been logged out!</div>';
}
?>
also inside that if statement you can clear user session aswell..
There are many solutions to this, but almost all of them require logout.php to pass the message, and index.php to have code to display the message.
My preferred method is to pass the message as a URL parameter. Use header to re-direct, use base64_encode to shorten the text in the url, and url_encode to make sure that the URL doesn't get junked up.
//Redirect with success message
header('Location: /index.php?msg=' . urlencode(base64_encode("You have been successfully logged out!")));
Then, on your index.php page
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
Edit: If your headers have already been sent out (have you echoed out some text on a line above these?), you can use Javascript to do the redirection.
Replace header('Location: ') with this: echo '<meta http-equiv="Refresh" content="0;url=http://example.com/index.php?msg=' . urlencode(base64_encode('You have been successfully logged out!')) . '">';
You could use "Noty" plugin to enable notifications on your web-app.
see here: http://needim.github.com/noty/
Implementation should look something like that:
Redirect the user to index.php?logout=1
Use the Query String parameter to populate a hidden field.
Use noty to display the hidden field value when page loads.
Here is a code example:
<?php
if(!empty($_GET['logout'])){
echo '<input id="logoutMsg" value="You have been logged out!" />';
}
?>
<script>
var logoutMsg = $('#logoutMsg').val();
var noty = noty({text: logoutMsg });
</script>
If you want to redirect right after the success message, then use the following code:-
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!
echo '<meta http-equiv="Refresh" content="0;url=http://url.which.you.want.to.be.redirected.to">';
}
}
?>

Categories