End Session in all browser after logout.php - javascript

I currenly have this on my logout.php
<?php
//LOGOUT.PHP
session_start();
//// unset all $_SESSION variables
session_regenerate_id();
session_unset();
session_destroy();
$_SESSION['logoutsuccess'] = 'You have successfully logged out.';
header("Location: index.php");
exit;
But after changing password using changepassword.php that has logout.php in the end. It just destroy the session on current tab. But it doesn't destroy the session on the other browser/tab. TIA!

Do this:
$_SESSION = array();
session_destroy();
setcookie (session_name(), '', time()-3600);

You can try this
//LOGOUT.PHP
session_start();
//// destroy all $_SESSION variables
session_destroy();
echo "<script>alert('You have successfully logged out.')</script>";
echo "<script>window.open('index.php','_self')</script>";

What you are attempting to do isn't easy when it comes to pure PHP. Javascript will be your friend in a situation like this.
If I were to implement this I would create something in JS that checks every x amount of seconds/minutes with the backend to see if the password has changed. This will require a separate endpoint that is specifically for this check.
Here would be a rough outline of what I would consider doing:
When the user logs in take the username and hashed password to create a hash of that data using something like $userAuthHash = sha1("{$username}${password_hash}) and save that in the user session.
In your page (in the header more than likely) display the created hash. This is generally best to do in a meta tag in the header (ex: <meta name="user_auth_hash" content="<?php echo $userAuthHash; ?>">). You can obviously set this up however you want as long as you can look it up using JS.
Have the JS script get the value of the hash from the meta tag and every x interval send this to the validation endpoint. The endpoint should in some way indicate if the users token is still valid.
If the users token is no longer valid you can have the JS script redirect the user to the logout script as needed.
There are a lot more complex ways of doing this but this is one of the easiest ways of going about this that I know of.
Also remember not to over think these things when building software. Security is important but imagine the case where an account gets hacked and the hacking party changes the password. Your now legitimate user has been logged out and thats never any good. This would be a case where you would need to evaluate your initial strategy and possibly implement an email that forces the user to validate a password change before it is persisted to the database. Just some food for thought.

Related

How can I make the page to show success message on submission to telegram and redirect? [duplicate]

I'm trying to create a Session-Based flash message in PHP:
In register.php page, I set the session as follow:
$_SESSION['flash'] = 'Registered';
Then, after redirecting user to the home page, I printed the flash message:
if (isset($_SESSION['flash'])) {
echo $_SESSION['flash'];
unset($_SESSION['flash']);
}
The session is started in both pages.
The problem is:
I get the flash message in the home page only if I remove the unset function, and then the message is always printed.
I wrote a library just for this type of issues: https://github.com/tamtamchik/simple-flash.
Once you have it installed you can do this:
// put message not session
flash('Some error message', 'error');
// print it after redirect
echo flash()->display();
It'll generate Bootstrap friendly alert messages.
I just solved my problem by adding exit after redirecting user to escape the execution of the register page, so the session won't be unset in the current page before using it in the next page.
Please note that session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.
Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:
<?php
session_unset();
session_destroy();
?>

Set SESSION on php and remove it via JAVASCIPT [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

How to prevent user to change javascript button disable() function?

Creating a forum on localhost. When user clicks on the button to post the question, my javascript function disables it(when the question was asked) to prevent question spamming. Everything okay with that, but:
Here is the code which is in /scripts/scriptname.js
function disable() {
document.getElementById("submit-img").disabled = true;
}
disable();
If the user changes this code above to false, the user can post various questions, because he can change it to: .disabled = false
Unfortunately, you cannot. Any form of front-end validation will not protect your server or database from spammers hence a back-end validation is required. Depending on what back-end language and framework you're using, you'll need to keep track of the user's IP address (assuming there is no form of authentication) and set a timestamp in your database that will prevent that specific IP address from sending requests to the endpoint you're trying to protect.
The way you are going about with it is wrong. You should allow only registered and verified user to access and post content to your forum. Your implementation is javascript base so it can be hacked.
It should be done server side. At least, you should create a database where you should track all users activities via something like their login session data, ip address, emails etc. You can set a counter to count number of content to be posted by users on a particular time and then banned or stop any offending user.
While double registration by users are not easily avoided but you can limit it by asking each registered user to verify their email via a link sent to them upon registration.
You can also set up a captcha eg Google recaptcha to limit bots access
Infact, what you are trying to implement is too broad from security point of view.
If security is not much of your interest you can try this little sample code below. The tracking is based on session. just remember that if users clears session cookies, he can still bypass
Based on your request. You can use session to track users submission count. This is not security proof as I stated earlier but it will give you an insight into building your own app. However its far better that doing it in a javascript which your users/clients can easily abused....
The code below will hide submit button if user submit more than 2 times
<form action="" method="post">
Enter name<input type="text" name="uname">
<?php
error_reporting(0);
session_start();
if($_SESSION['att'] >=2){
// hide submit button
}else{
echo '<input type="submit" value="submit">';
}
?>
</form>
<?php
//session_start();
// set up session counter
echo $_SESSION['att'] = $_SESSION['attempts']++; //increment
$name='';
$uname='';
$name = $_POST["uname"];
echo $_SESSION['uname'] = $name;
?>

Keep SESSION php after 3° pages refresh

i have a issue with my SESSIONS, on the first page the user clicks on a anchor, then if the user is logged in will be redirected without problem, but if not, first he will pass through login page, but when the user reach thelogin page, the variables are missing. (The login page occurs after the redirect page). So i have saved the SESSIONS with $_GET parameters.
How i can keep the current SESSIONS to redirect the user after the login?
Thanks!
EDITED
Page: retailer.php (this page is where its fired the parameters)
<a href="/go2store.php?rid=<?php echo $row['slug_title']; ?>&c=<?php echo $row_coupons['coupon_id']; ?>" onclick="javascript:window.location.href='<?php echo $row_coupons['logout_url']; ?>';" target="_blank">
Page: go2store.php (this page is where i'm saving the SESSION)
$_SESSION["myCupon"] = "/go2store.php?rid=".$_GET['rid']."&c=".$_GET['c'];
Page: redirect.php (This page its checking if the user is logged in, if yes, redirect to the URL on the SESSION, if not will send to login.php)
Page: login.php (here i have this on top of the code)
session_start();
$_SESSION["myCupon"] = "/go2store.php?rid=".$_POST['rid']."&c=".$_POST['c'];
But it comes empty, its not returning any values after the redirect.php page.
As noted by a user in the comments, you need to include:
session_start();
At the top of each page to carry session variables across pages, otherwise it won't recognise the vars you set initially.
We don't know how you're organising your code, but this needs to be present both before and after potential login.
You can easily set/get $_SESSION variables prior to login or indeed set/get upon login from other vars you might use in pages that aren't yet authenticated.

Easiest way to store data from web site (on server side)

I have very simple web site (which is actually single page), there is one input field and a button.
I need to store data submitted by users somewhere on server side. Perfect way could be simple text file and new lines appended to it after each button click. Log file will be also ok.
As I understand it is not possible with JavaScript itself. I'm looking for easiest solution, preferably with no server-side programming (but if it is required, it should be as easy as possible and work out-of-box). I can use some side service if it could be helpful.
Please help.
Thanks in advance.
UPD. Just want to rephrase the main question. I do not really need to store something on server side. I need to collect some input from users. Is it possible? It would also be ok if it for example will be just sent to my e-mail.
For a very simple form-to-server-log script:
Your form:
<form action="save-to-log.php" method="POST">
<fieldset>
<legend>Add to log</legend>
<p>
Message:
<textarea name="message"></textarea>
</p>
<p>
<input type="submit" value="SAVE" />
</p>
</fieldset>
</form>
Then save-to-log.php
<?php
$log_file_name = 'mylog.log'; // Change to the log file name
$message = $_POST['message']; // incoming message
file_put_contents($log_file_name, $message, FILE_APPEND);
header('Location: /'); // redirect back to the main site
if it's a unix host you'll need to add 755 permissions to the directory of the log so PHP has access to write to it. Other than that, you'll have a form that keeps appending information to mylog.log.
Follow-Up
If you don't necessarily need it store on the server (you mentioned email) you can use the following instead as the PHP script:
<?php
$to_email = 'kardanov#domain.com';
$subject = 'User feedback from site';
$message = $_POST['message'];
// this may need configuring depending on your host. If you find the email isn't
// being sent, look up the error you're receiving or post another question here on
// SO.
mail($to_email, $subject, $message);
header('Location: /');
You can't store information on the server without some sort of server side script.
There are two different places to store data, on the client and on the server.
On the client side, there are lots of ways from cookies to Store.js, however it sounds like you want to store the information on the server.
To store on the server you need some sort of application that can receive posts from javascript/http and save them in a file.
In your case a very simple PHP script like the below would be perfect:
<?php
//Was the request (post or get) parameter data supplied?
if(!empty($_REQUEST['data']) {
$file = 'log.txt';
$data = $_REQUEST['data']."\n";
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
?>
How about dumping JSON to a file with PHP and then loading it on request?
How to safely write JSON data to file using PHP
If you want to get the data sent to your email address, there are several free services that can do this without installing any server side applications... A PHP or CGI script is still being used but it is hosted by the service, not by you.,
All you have to do is paste some code into your site and then all submitted data will be sent to your email address., A lot of people don't have the know-how to do this on their own, or their hosting service will not allow send-mail to work. Thats why these services exist. And of course most of them are supported by ads that are placed in the email that you get from the form. Anyway, here is the link for a good service I found. You can also Google "Free Form Processing" to find more.
https://secure.tectite.com/hf/auth/GetStarted?WWWTECTITE
Hope this helps.

Categories