how to delete/destroy/unset a specific php session - php

I need to delete/destroy/unset a specific session
$('#btnlogout').on('click', function(){
$.post('pro.php', {fn: 'btn_logout'}, function(data){
location.href = location.href;
});
});
pro.php
function btn_logout(){
//$_SESSION['id'] = 5; //this works
unset($_SESSION['id']); // doesn't work
destroy_session(); // doesn't work
}
echo $_SESSION['id'] on main page always gives me a value
here - How do I destroy a specific session variable in PHP? unset($_SESSION['id']) is accepted answer, but I tried so many times - doesn't work

The unset method itself does the trick but until the page is refreshed it echo the last instance. you can try this
session_start();
if(isset(($_SESSION['id'])){
unset($_SESSION['id']);
die();
header ('Location: index.php'); //optional line, any other page can be used
}

Related

PHP + Session doesn't login at first time

My login system only logs in if I do it 2 times. In the first time, it doesn't log in (automatically).
I have a simple form with username and password, with action="login.php", which as you might think has the whole code for verify login, etc..and then, in the end, if everything is ok:
Cookie::set('page-main-login-cookie', serialize($arr), time()+60);
header('location: ../index.php');
In the index.php (which contains the form that calls login.php), in the top of the page:
ob_start(); session_start(); include('cookies.php'); include('sessions.php');
After the </html> tag:
if(Cookie::Exists('page-main-login-cookie')){
$data = unserialize(stripslashes($_COOKIE['page-main-login-cookie']));
if($data['status'] == 1){
Cookie::set('email', $data['email'], time() + (86400 * 7));
Session::set('email', $data['email']);
echo "<script type='text/javascript'> page_redirect(); </script>";
}else{
echo "<script type='text/javascript'> page_error(); </script>";
}
Cookie::Delete('page-main-login-cookie', time() - 3600);
}
And while I'm writing this topic I wonder if the problem might be in the javascript. The code for page_redirect() is the following:
function page_redirect(){
alert("Done!");
setTimeout(function(){
location.reload();
}, 1500);
}
What have I tried so far?
Changed header('location: ../index.php'); to header('location: http://www.mysite.com');
Added session_write_close(); after Session::set('email', $data['email']);
None of them worked.
Probably because your log in code comes after your html, so it appears like you are not logged in even though the script does log you in at the end of the script.
Typically you would want to keep your PHP and HTML as separate as possible (in different files), and do all of your PHP business logic first, then output all the HTML.

why my echo doesn't work before a header function header(location:home.php);

why my echo doesn't work here in this code?It goes directly to the function header().
if($result){
echo("<script> alert('User Successfull Added')</script>");
header('location:home.php');
}
In order to make your code example work, you need to put it inside an if/else condition like so, if you want it to work, but since I only see what you posted as code, am putting this in as an example:
<?php
if($result){
echo("<script>alert('User Successfully Added')</script>");
echo("<script>window.location = 'home.php';</script>");
}
else {
header('Location: elsewhere.php');
}
Actually thy echo is working. but we cant see the message because at the same time the page redirects to the home.php page.
If you want to alert to display the alert message use jquery post. or php session variable
Assuming you want to both display the alert & redirect to home.php, why don't you just try setting a SESSION (or other global variable) and then check if it's set at the start of the redirected page?
Such as:
<?php
session_start();
$_SESSION['usercreated']="Y";
header('Location: elsewhere.php');
?>
and then on home.php at the start of your php code:
<?php
session_start();
if(isset($_SESSION['usercreated'])){
echo("<script> alert('User Successfully Added')</script>");
}
//....
?>
Sorry, I can't add comment here. But I think what you want to do needs Java and replace alert() with confirm()
var r=confirm("User Successfull Added")
if (r==true) // if user click OK
{
window.location.assign("home.php")
}
else // user click Cancel
{
}

Starting a PHP session on a jQuery function event

I've got a simple jQuery function and at a certain point (let's say on a button click) I'd like to start a PHP session.
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//here I'd need a way to trigger the session.
});
});
I would assume starting a session from PHP can be done as easily as changing a PHP variable. For example - the PHP can be something like:
<?php
$testVar = null;
if(isset($testVar)){
session_start()
$_SESSION['sessionStarted'] = $testVar;
}
?>
Is there a way for such as session to be started?
<?php
session_start();
if(isset($_GET['login'])) {
if(isset($_SESSION['sessionStarted'])) {
echo 'session is already set';
} else {
$_SESSION['sessionStarted'] = $testVar;
}
}
?>
and client-side:
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//code to redirect to index.php?login=true or make some ajax GET call, doesnt matter
});
});
then you can add like php checks, if session exists, do not echo loginPopupButton and so on :)

read data returned from jquery .post

I have a page that I want redirected to the login page if a user is inactive for 1/2 hour. I am new to jQuery and it has taken me awhile to get this far.
So basically the user logs in they are redirected to the home page. I have jQuery running on the home page that posts to the check_time.php page every 10 seconds. if they have been inactive for more than a 1/2 hour, then session is destroyed and they get redirected to the login page.
I have everything working except checking the value of the "data" that is returned from the check_time.php page.
here is the code on the home page.
ini_set('session.gc_maxlifetime',1800);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_start();
if($_SESSION['admin_login'] != $password){
header('Location: index.php');
exit();
}
if(isset($_SESSION['last_activity']) && (time()-$_SESSION['last_activity'] >1800)){
// last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
header('Location: index.php');
exit();
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function timedCount(){
$.ajax({
type: 'POST',
url: "check_time.php",
success: function(data){
if (data == "LOGOUT") {
window.location = 'index.php';
}
}
});
setTimeout("timedCount()",10000);
};
</script>
this is the code on the check_time.php
<?php
session_start();
if (isset($_SESSION['last_activity'])){
if(time() - $_SESSION['last_activity'] > 1800){
session_unset();
session_destroy();
echo "LOGOUT";
}
}else{
echo "LOGOUT";
}
?>
I asked this same question last week I wanted to post my latest code so I stated a new question. I really greatly appreciate your help!!!!!
try :
if (jQuery.trim(data) == "LOGOUT")
{
...
}

PHP: Detect Page Refresh

I have a page action.php on which I run an SQL query through the code, so that whenever the page is viewed the query runs like its like counting page views
<?php
mysqli_query("UPDATE ****");
?>
The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.
Question: How to avoid it ?
What I am looking for is a simple solution so that I can check
if( page was refresh ) //some condition
{
do
}
I found this snippet here, and it worked perfectly for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}
Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' || $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
if($pageRefreshed == 1){
echo "Yes page Refreshed";
}else{
//enter code here
echo "No";
}
You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.
If you just want to run it once for a user, I would set a session cookie and then use an if() statement.
<?php
session_start();
if (!$_SESSION['loaded'])
{
// insert query here
}
$_SESSION['loaded'] = true;
?>
i have solved the problem ... HURRAHHH with no session & no cookies
the solution is a combination of PHP : AJAX : JavaScript
the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is
function runQUERY()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","doIT.php",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following
<head>
<script type="text/javascript">
function checkRefresh()
{
if( document.refreshForm.visited.value == "" )
{
// This is a fresh page load
alert ( 'Fresh Load' );
document.refreshForm.visited.value = "1";
..call you AJAX function here
}
else
{
// This is a page refresh
alert ( 'Page has been Refreshed, The AJAX call was not made');
}
}
</script>
</head>
<body onLoad="checkRefresh()">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
and in your doIT.php simple add your PHP code which you were going to put in the normal page
<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
//here you get the url behind the domain.
$currentPage = $_SERVER['REQUEST_URI'];
//if the session current page is not set.
if(!isset($_SESSION['currentPage'])){
//set the session to the current page.
$_SESSION['currentPage'] = $currentPage;
}
//check if the session is not equal to the current page
if($_SESSION['currentPage'] != $currentPage){
// if it's not equal you set the session again to the current page.
$_SESSION['currentPage'] = $currentPage;
//set the query you want to use
}
This can work in your scenario:
if(isset($_GET["token"])) {
$view_token = $_GET["token"];
} else {
$new_views = $views + 1;
// UPDATE VIEWS
$view_token = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
header("Location: ?token=$view_token");
}
If the user has a token in the URL, the view count will not update. Therefore, if the user tries to refresh, it will not update the view count. When the user does not have a token in the URL, the view count updates and refreshes the page WITH a token. It is thinking outside of the box but it works!
You can save a cookie that will be associated with the present page and if any link is clicked, update the cookie with the new page name.
Assuming the above is done in Javascript, you can send this updateCookie information to the server to notify about a new page hit.
Or another approach could be, you can specify a HTTP HEADER that specifies after how much time the cache expires on a page and that way, the browser wont even send you a request about page load/refresh.
See http://www.mnot.net/cache_docs/#IMP-SCRIPT for information about CACHING
Also , check out Etag vs Expires in HTTP - ETag vs Header Expires
if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
$_SESSION['status'] = null;<br>
}

Categories