Yii: Does any way to keep the session unclear after logout - php

I use the session value to check the current language, but we I logout, all sessions values are cleared and the language changed to default. does any way to keep the session unclear after logout.

Using session for storing the language is not a good option ( truth is its worst).
What to use then ?
You should either use the cookies as language is not important or secret data (I think so). Even if the user somehow loses the language he selected, he could select it again and all that will be stored in cookie for as long as you want. To know more about cookies in Yii click here
BUT IF
You for some reason hate cookies(although I will recommend cookies only) then
the second option is appending the language with the url in every request like ?lang=en. This might be a tricky one as you will have to take care of this parameter in every request and url.

How to keep current language after user logs out ?
You can use setComponent() method to set, application components dynamically.
Try by creating a method, say:
public function setLanguage(){
// When User log in is success, raise a flag, and set in by:
// Or more specifically, donot copy and paste it, at least give some research and do it something like this.
Yii::app()->setComponent('language','en');
}
And use it, by Yii::app()->language;
So, you can here dynamically set and reset your language component.
As Let me see said, using session for language is not a good option.

I think this will work not much sure .
Use Yii::app()->user->logout(false). It will only remove the authentication related information from session and keep the other data there intact.

Related

Best practice to save user input for the duration of session Drupal 8

I am working on a website with Drupal8. I am wondering what's a good practice to store user-specific data that is important for the length of the session. As an example, let's say a user is a student in a school and is taking different classes/courses. After login the user chooses one of the courses and then only gets to see all the content/other students/... of this particular course.
The easiest solution I can think of is just storing the data in the $_SESSION object. But then all the views in drupal would have to read the data from this object and as far as I know this was possible in Drupal7 with custom php code, but not anymore in Drupal8 views.
Also additionally, if I'd like to store the user's default preference permanently, I could create a custom content type 'user_config_data' or something like this, where I store information that is important for the current session (and needs to be accessed in each view etc) and also a value for a default choice (i.e. the course the user wants to see as default after login)
The latter could probably also be achieved via cookies?!
Something else I did not think of ?
Is any of the approaches more/less advantageous in terms of performance, good coding practice, modifiability ? Thanks for any thoughts on this.
The PrivateTempStore is what you're looking for. You can use it to store data per user over the entire session.
You can use it like this
$tempStoreService = \Drupal::service('user.private_tempstore');
// Set a variable in the tempstore
$tempStoreService->set('user_data', $data);
// Get a variable from the tempstore
$userData = $tempStoreService->get('user_data');
This works over the entire session of a user. In case you need to share data between users you can use the SharedTempStore
I did more reading on that and I am now using $tempStoreService as shown by VJamie. To make the argument available in a Drupal 8 view I created a custom module to implement hook_views_pre_view() and add my value as an argument to the view. Then I am using a contextual filter in the view to make sure the argument is used. However, the preview for the view works nicely, but on the real page the view gets cached and the output is the same no matter what argument I give. Only when disabling caching for the entire view it works. Is this a standard approach or is there a different solution to the caching problem with contextual filters ?

Handling expired sessions

Alot of my controllers have functions that look like this. What is the best measure to take with CI when a session runs out and a function like such is called?
$this->foo_model->create_bar($this->session->userdata('userid'), $bookId);
I don't fully get your question maybe, but when you call $this->session->userdata('something') for an expired session it will simply return FALSE.
So, the best method would be checking if the variable isn't FALSE? As you would do with any other variable that might not be the value you want:
if($this->session->userdata('userid')){}
//or check it into the model's method, wherever you prefer
Where and when to do that strongly depends on your design. If you always need to do the same check you might want to make it a library or a model's function, so that you just need to write your code once and just call that method. If you need it done before anything else you might consider placing it in the constructor, or as #Jordan Arsenault suggested, create a parent MY_Controller which does the check, and all your regular controllers extends it. Really, this depends on you architecture and you didn't provide enough info to answer that.
All I can say is make your methods fault tolerants, always check for the correct value before feeding the rest of your code (if an expired session breaks your workflow)
You can use cookies to revive an expired session.For example you can create a token for users when they login to your application .This token has a related userid that your application knows globally then save a cookie on the user machine that contains the token.each time the session expires ask for the client cookies and see if this cookie is available then with its userid re-create the session.if there's no token available redirect your user to a page telling him what has happened and ask him to login again.
When the user logs out delete the token and the cookie

Passing variable over to a new HTTP Request

As the title says, is there another way to pass a variable from "current" page over to "next" (new HTTP request) page without using sessions/cookies/$_GET?
Well, I guess $_POST could be an option too, but the thing here is, that I want to pass this variable from already executed $_POST back to off-the-post environment page, but inbetween I'm having a redirect, to disallow reposting the same form.
In other words, basicly, I'm trying to "make" a seamless PRG, but sessions/cookies/$_GET is not an option.
And yes, I'm working with classes (hence the oop tag). Therefore maybe some kind of magic functions, or output control?
This has to work within PHP environment, no JavaScript or other non server side language.
I also have a bad feeling that it's impossible, but hopefully I'm wrong, and there is a solution.
Thanks in advance!
update no. 1
Basicly, I want to create a PRG with response.
Inside this $_POST I'm adding data to database. I want this response to hold information whether this database query has been successful or not. Kind of make this $_POST process almost invisible to the user. And yes, display a response with the result later on.
All of this happens in one method:
if($_POST){
// insertion
}else{
// display no-post environment, if response exists (therefore posted) display response too
}
Something like that...
Sessions is not an option because this is meant to be some kind of API.
update no. 2
Huh, let me rephrase the question a little. Well, it seems that I don't actually need to pass the variable over. What I want to do, is to have 2 different results after POST so on next page load I could know whether the actions in POST has been successful or not. So, what other options are out there without using sessions/cookies/$_GET to get this result?
Currently there is:
temporary database usage: a good option, but I'd like to see different options;
Since you're already using a database it seems like the easiest way to handle this would be to update some kind of temporary table with the information you want based on the post call, then on the page you're doing a header redirect to, read the information in that table. With the constraints you've placed on this (no GET, SESSION, Cookie or Javascript) you're not going to be able to maintain a variable when you redirect from one page to the next.
So leverage that database and take the work off of PHP. Initially I was going to suggest utilizing cURL but I don't think that will help here (though you may want to look it up if you're unfamiliar with it, as it might be what you're looking for)
HTTP is a stateless protocol; thus, there's not going to be an easy, built-in way to add state. That said, I think sessions are the best way to accomplish what you want to do. If what you're doing isn't in the browser, maybe try some sort of session key setup (like the Facebook platform uses).

Return a result in the original page

When the user submit his data, I take him to a different page where plenty of calculations are made, then I redirect him to the original page with a simple :
<?php header("Location:http://mysite.com/index.php");
The problem is I need all the variables and results to be show in this page, but they are obviously stored in the other one, so I need your help please :) !
Thank you for reading this !
PHP sessions.
session_start(); as the first thing on both (and all of your pages where you want to access this data).
set the variables you want to access as such:
$_SESSION["somekey"] = "somevalue";
then you can recall them on any of the other pages.
this functionality is reliant on session cookies, of course.
You can accomplish this through the use of sessions.
Don't forget you could use a database.
Sessions would be your best choice. See the other answer for the link to the php manual.
You could append them to the URI, but depending on field length and field counts that could be very messy (or not even possible, if too long).
If neither of these are options (too long, can't use cookies), you could can pass the session key along in the GET param. You can then use sessions normally.

How to use sessions in place of a querystring

Using PHP.. I have a small app that I built that currently uses a querystring to navigate and grab data from a database. The key in the database is also in the string and that is not acceptable anymore. I need to change it. I would like to hide the db key and use a session in place of it but I'm not sure how to do that. In fact, there are also other variables in the query string that I would like to use sessions for if at all possible.
page.php?var1&var2&id=1
This is what my string looks like. I am looping through the results in the database and have given each row the id so that when the user clicks the row they want, but I'm not sure how I could do this with a session.
Does anyone have any ideas?
Thanks
EDIT:
I'm developing an email type system where senders and recipients are getting and sending mail. Each piece of mail that is stored on the server will have its own unique key. Currently, I am using that number to retreive the message but the problem is that I don't want people to change the number and read other people's mail. I can probably use a GUID for this or even some sort of hash but I really hate long query strings. I was just thinking it would be so much cleaner if there was a way to "hide" the id all together.
UPDATED (Again ... Yeah, I know.)
Allowing access to a particular set of data through a $_GET parameter is much more accessible to any user that happens to be using the application.
UPDATED
For storing a private record key, you are probably going to want to use post data, and if you really want it to look like a link, you can always use CSS for that part.
Honestly, the best way to stop people from reading other people's mail is by having a relationship table that says only X person is able to access Y email (by id). That or have a field that says who is the 'owner' of the email.
The fact is that users can still get access to POST parameters, and can easily forge their own POST parameters. This means that anyone could realistically access anyone else's email if they knew the naming scheme.
In an ideal system, there would be a Sender, and a Recipient (The Recipient could be comma separated values). Only the people that are on one of those columns should be allowed to access the email.
How To Use Sessions (From Earlier)
First start off with calling session_start(), and then after that check for variables from previous scripts. If they aren't present, generate them. If they are, grab them and use them.
session_start();
if(!isset($_SESSION['db_key']))
{
$_SESSION['db_key'] = // generate your database key
}
else
{
$db_key = $_SESSION['db_key'];
}
Sessions are stored in the $_SESSION array. Whenever you want to use $_SESSION, you need to call session_start() FIRST and then you can assign or grab anything you like from it.
When you want to destroy the data, call session_destroy();
Also check out php.net's section on Sessions
Your question isn't too clear to me, but I understand it like this:
You need some variables to decide what is being displayed on the page. These variables are being passed in the URL. So far so good, perfectly normal. Now you want to hide these variables and save them in the session?
Consider this: Right now, every page has a unique URL.
http://mysite.com/page?var1=x&var2=y
displays a unique page. Whenever you visit the above URL, you'll get the same page.
What you're asking for, if I understand correctly, is to use one URL like
http://mysite.com/page
without variables, yet still get different pages?
That's certainly possible, but that means you'll need to keep track of what the user is doing on the server. I.e. "user clicked on 'Next Page', the last time I saw him he was on page X, so he should now be on page Y, so when he's requesting the site the next time, I'll show him page Y."
That's a lot of work to do, and things can get awkward quickly if the user starts to use the back button. I don't think this is a good idea.
If you need to take sensitive information out of the URL, obfuscate them somehow (hashes) or use alternative values that don't have any meaning by themselves.
It completely depends on your application of course, if the user is accumulating data over several pages, Sessions are the way to go obviously. Can you be a bit more descriptive on what your app is doing?
Edit:
but the problem is that I don't want people to change the number and read other people's mail
If your primary concern is security, that's the wrong way to do it anyway. Security through obscurity is not gonna work. You need to explicitly check if a user is allowed to see a certain piece of info before displaying it to him, not just relying on him not guessing the right id.
There are some examples on how to use $_SESSION on php.
Registering a variable with $_SESSION
The issue with using sessions for using it in place of S$_GET or $_POST is that you need some way to read the user's input so that you can store it in the session, and you need a way to trigger a page refresh. Traditional means is via hyperlinks, which defaults to GET (unless you use Javascript) or forms, which defaults to POST.
Maybe ajax will help you here. Once the user has enter info into a form or a checkbox, use JS to send a request to insert the info to the PHP and send info back, whether it is to refresh the page or to fill a with content.
Hope this helps

Categories