PHP sessions and session destroy - php

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

Related

previously inserted value gets inserted automatically on page refresh

What could be the query or what could be the solution of inserting values in database through html form via PHP but everytime I refresh the page the previously inserted value gets inserted again?
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
Anytime you refresh the page you are resubmitting the POST variables, so the PHP still runs. Additionally, your query is in danger of SQL injection. Consider using PDO.
As stated previously (and for my own understanding), every time you refresh the page, the request is sent again. Mind me for forgetting that, thank you #ADyson.
So, a solution for that would be redirecting the user to the same form after the insertion is made.
Assuming this file would be test.php, for example:
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
sleep('3');
header('Location: /test.php');
exit();
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When you reload the page the browser asks you to re-submit the request, so the value gets transferred again. So put a condition when you insert data that will check if the record already exists or not.

$_SESSION not working/ sending out wrong result in 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');
}
?>

PHP Session Variable gets lost between pages.

I have made a simple login page to access an application. The login works fine at times, but from time to time, I'll have trouble logging into the system, as the session data will be lost on the last page.
The files I have are
1) login.php, with Login name and Password Field.
2) loginprocess.php - Which will connect to the database to check whether there username and password exists, after which a session is created.
3) listing.php - Which will be the final page if login is successful.
The loginprocess.php page will create a session variable if Login Name and Password exists in the database. It'll then redirect to the last page.
$selectstring = "SELECT * FROM logintable WHERE username='".$loginname."' AND password='".$pass."'";
$result = mysql_query($selectstring);
//IF YES THEN GO TO MAIN
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
//CREATE SESSION
session_start();
// Set session variables
$_SESSION["loginname"]= $loginname;
header("Location: listing.php");
exit;
}
else {
echo "ERROR";
header("Location: login.php?message=error");
exit;
}
At the top of the last page, listing.php, I'll have a script that will redirect if session variable is empty.
session_start();
if (!isset($_SESSION['loginname']) && empty($_SESSION['loginname'])) {
header("Location: login.php");
}
Am I inserting session_start(); too late on loginprocess.php ?
First, move the session_start(); to the top of your file.
Next, you need to do an OR instead of an AND in your if, because the login name is either unset or empty.

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">';
}
}
?>

Errors for changing variables content depending on session status

I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
It seams your variables don't hold the expected values when the $logOptions_id != $id runs, or you either forget to start the session. I don't see reference where $logOptions_id gets assigned. Use your IDE tool to debug the code.

Categories