So I am aware of these two common ways of passing variables across php pages.
1. PHP SESSIONS
I understand that $_SESSION is a php global variable that can hold variables across php pages during the session of the browser.
It works well but my concern with it is if a user for what ever reasons, decides to type the url of a page or goes into their history and accesses a url page for the website, the $_SESSION variable may not be set, if it was expecting the user to get to this page from a set route/path.
In addition, if a user goes into another page, and the page sets an already defined $_SESSION to another value, and then decides to go back to the previous page, the $_SESSION variable is not correct for that page, causing many errors.
2. URL passing
This is by far the most reliable in my opinion. The only concern I have with this, is the pages can get rather messy with long URL's.
page1.php?postId={variable goes here}
passing 4,5 or 6 variables can get a bit messy, I also need to encode then or encrypt them. The URL can get rather long, and I am not sure how I feel about passing variables across the URL.
My Question:
What is the best way to pass variables from one php page to another. Are the two methods above the best way to go about it, or is there another my efficient way. Also if efficiency isn't the issue, then what is the most secure procedure/method.
Thanks for your time.
This is largely going to depend what you're trying to do? $_SESSION variables and $_GET variables largely have different purposes in web programming (although, yes, you could force some sway between the two).
The question you need to ask yourself is "is the variable storing information on the user OR directing the webserver to do something" if it's the former then use $_SESSION if it's the latter then $_GET.
You wouldn't for example want to pass loggedon=true as a GET variable (ignoring the security implications) because you would have to update every single link on the page to have the query string appended to it which, as you say, would lead to some untidy URLs.
SESSION
Is most commonly used for storing information about a user. Some examples:
Log on status
Shopping basket
Session preferences
For example when a user is successfully logged on you will want some way to remember that between page loads:
session_start();
$_SESSION["loggedon"] = true;
In every subsequent page request you can then check:
session_start();
if(!$_SESSION["loggedon"] ?? null){
echo "ERROR: You shouldn't be here!";
exit;
}
Note that $_SESSION is only accessible to the server, can't be directly accessed by the website user, and is persistent until the session closes.
GET
On the other hand is sent with every request and is typically used when you want to pass non-sensitive information from the user to the webserver. Some examples:
Language preferences
User input (e.g. a search query when using a search engine)
Forgotten password secure codes
Suppose you have a cookery website and 1000 recipes. You would likely only have one page to show the recipe and pass a GET variable in the URL to indicate which recipe should be loaded
http://www.mycookingwebsite.com/recipe.php?recipeid=477
Note that GET requests are visible to the user, can be modified, and show up in history etc. as well.
N.B. Do not pass sensitive details (e.g. username/password) over GET - not least because they would show up in the browser history!
You mention passing variables from one page to another. But I'm not quite clear on whether you mean Server->Server (SESSION) OR Client->Server(GET)?
An example of this all coming together would be in the case of a shopping cart:
At the back end you have an array stored in your session with the items in the cart, this is persistent throughout the session. On the client side you have the ability to send a GET (most people would probably POST) request to tell the server about the new product you want to add to the list.
If your primary concern is that users may find themselves at the wrong "stage" then I suggest building in some checks to make sure that they are in the right place at the right time.
For example given a quiz with 10 questions... If the user clicks a link which drops them at question 5 you check to see if they've already answered questions 1-4 and then act appropriately depending on the answer.
Related
I have a (hopefully) quick question regarding sessions. Whilst I have used sessions extensively, I have not used them in a situation whereby the values change depending on a users actions.
After logging in to my application, a user can select a company area, which has many levels of pages and folders. All of these pages will need this 'company_id'. At the moment I send the company_id via GET, but as I get deeper into the application this is becoming increasingly hard to maintain, with various other data being stored in the URL.
Therefore, when a user selects their company, I could set their company_id in $_SESSION array. However, when a user changes company, I would then need to change $_SESSION['company_id'] to the new value.
Is this a good use of sessions? I could potentially clean up my urls by using session data rather than always using GET, but I am unsure if this is a recommended way of using sessions.
Thanks in advance
This is a bad implementation of the HTTP design philosophy. All HTTP requests should be self contained, RESTful. All information needed to get a specific page should be present in the request itself (URL, headers and body), not dependent on hidden state.
Super trivial example: you can't copy a URL to someplace or someone else and have them see the same page. The content of the page is dependent on session state, which has been laboriously set through the visit history of several previous pages. To return to this same page, you need to retrace the same steps, recreating some hidden server-side state to arrive at the same page.
This gets even more complex and messier if you take into account that a visitor may want to open pages requiring different states in two or more simultaneous tabs/windows.
All this isn't to say that it can't work, only that it's hideously complex and will break the usual expected behaviour of browsers, unless you really bend over backwards to somehow prevent that.
If the many levels of pages and levels are per-company, you can put the company_id in a specific include file - this part of the site being dedicated to a given company.
However if they're shared by multiple companies, and this is probably what you want, this is potentially misleading, or even dangerous depending on the user actions, since the user may jump to a given page (link...) and access a page with unexpected data linked to a company which ID is provided by the session or cookie.
You could dynamically build the links on a page, based on IDs, to ensure consistency during the navigation from that page. Any direct "jump" to another part of the site will not carry the ID with it (and the page may offer to select a company).
Depending on your web server and if you have control over it you could build the URL having "company ID" as an element of the URL path, not the GET parameters
Eg
http://example.com/invoicing/company382/listprices.php
using a rewrite (web server configuration) to change the URL to be actually used to
http://example.com/invoicing/listprices.php?compid=company382
(URL not visible to the user) that informs of the company ID via the GET parameters.
A short tutorial in W3schools about PHP Sessions writes the following:
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
I would like to ask you if there is something similar in Zoho Creator. The reason why I am asking is because I have an application with 3 pages (each page has an embedded form). Each page redirects to the other (1st Page -> 2nd Page -> 3rd Page) and passes data through them via openurl. The final result is an HTML Page with the data of these 3 Pages (they have a unique ID).
Let's say that I am in the second page and for some reason (electricity blackout, do another job and close the browser) I want to escape from the application and the next time to continue from the same point, is there any way to do that??
I can suggest you next way
On first page generate unique session Id for the user and pass this id as a parameter to next page in URL. You can crypt in this id pointer to record from first form for example..
I have made a quiz game using html & php and have URL as "localhost/game/ques1.php","localhost/game/ques2.php".
I have used sessions in it but a user can go the next question without answering question 1 by changing URL from localhost/game/ques1.php to localhost/game/ques2.php.
How to stop user doing that ??
Generally you'd do these things on a single page, but if you're sold on not doing it that way, you have a couple of options.
You could look into posting data to the questions as you go (include some hidden field that indicates the user started on question 1).
You could also include some dynamically generated token that you pass via query parameter to question 2.
You could use session variables to mark that each page was already requested, although I can imagine a number of ways that that could fail.
You could save cookies, although that's not a great way of doing it either.
I'd really look into just doing it all on one page. You don't have to show everything at once, I bet you could make the UI look very similar to what you've got now. But it'd be cleaner and probably load faster (since you wouldn't have to load all of your head and master page (or whatever) content for every question).
so I've hit a potential problem in my site....it's a post-based system, with the posts being in text files. Uses some Javascript and a lot of PHP.
When you make a submission on the form on the homepage, you are sent to a page where data is posted and processed, but you don't see it because you get redirected back. Then the homepage is changed based on what the post you made says. All that was working fine.
But now I'm trying to add a new feature that modifies the post you made, based on a button you hit which submits a hidden form using javascript, and sends to another process and redirect page you don't see, and it works fine until the block that I realized today. I don't know how to specify that the post being altered is the right one.
I anticipate a good amount of users of this site, so my concern is what if user X makes a post while user Y is making a post, and the post of user X becomes the top post, so user Y's options actually change user X's post.....
I was thinking of adding to the main processing page (the one that happens when you first submit) a COOKIE or something that would make note of the number of the line that post will become, by counting the number of the lines in that file at the time and adding 1 to it. Then checking it against the user's number (each user has a number) to see if it's that user's most recent post....but the problem is I don't know how I would pass that value around to be read in the next page.
Setting a COOKIE is out I think because the page both redirects, AND reads and writes to files. The only output to the page though are currently var_dumps.
POST/GET is out because to my knowledge the user would have to do SOMETHING to submit it, and the user's not even going to see the page.
Writing to a file would be messy if lots of users are trying to get their own data.
I think what I may be looking for is SESSION variables...but I don't know anything about those except that they're used to login to pages, and this site has no login.
To make things more fun, when a user posts the same content within a minute of another user, the first user's post is replaced and it gets a little +1 next to it...which makes it harder to check it against the user's number....
AND in the end I'm trying to use AJAX (which I dont know yet) to make the updates in real-time...now THAT is going to suck. But for now I'm worried about my static little site.
Baby steps.
Any ideas how to go about this??
Use Session variables, just as you have alluded. They aren't just used by login pages, they are used by everything. Sessions are the equivalent of server-side cookies / server-side storage, so you don't have to worry (as much) about your users tampering with them.
If you want to make life more difficult for yourself, you can json encode your variables and store them as an object in a database or even flat text file. But really, read up on sessions.
All you need to know is session_start(); before anything else then $_SESSION['var']=$yourvar; to save data and $_SESSION['yourvar'] to retrieve it later (such as on another page).
Ok, firstly this is not about forms this is about consistent layout as a user explores a site.
let me explain:
If we imagine a (non-ajax) digital camera online store, say someone was on the DSLR section and specified to view the cameras in Gallery mode and order by price. They then click onto the Compact camera's page. It would be in the users interests if the 'views' they selected we're carried over to this new page.
Now, i'd say use a session - am i wrong?
are there performance issues i should be aware of for a few small session vars ( ie view=1 , orderby=price) ?
Speaking of performances, there should not be much problems with either solutions.
Some things that have to be considered are :
With GET, if an URL gets copy-pasted (in a email or MSN), the other who will receive the URL will have the same GET parameters
is that a good thing, or not ?
On the other hand, session will not be shared, if an URL is copy-pasted
which means the first guy will say to the other "key, look at this", and the second guy will not see the same page ;; same thing with bookmarking, should I add.
GET is specific to each URL
While SESSION is shared accross all tabs of the user
Which means browsing with several tabs at the same time can cause troubles, when using Session, if you don't take care of that
I'd say use both. Store it in the session, but also put it in the get parameters for the page.
Why? This way the user is able to carry his options from page to page, but they are also in the URL so if he sends search results to his friend, his friend sees them the exact same way he did.
No, the session's performance will not degrade by putting those small variables in there. Unless you're storing monolithic arrays in your session, the vast majority of the time loading a session will be reading it from its storage medium (file, database, memcache, etc).
You should use GET in your case.
There is one simple rule in the web development: each page with different content must have it's own address. So, customer can save any page into favorites, send it to a frend. It's pain in the bottom then someone sends you a link to a particular page saying "Look!" but site uses frames and you land at the front page and dunno where to look.
You can save user's preferences into his profile/cookie (not session), but it should be reflected in the address bar as well.
Sessions being used for completely different purpose, shopping cart is an example.
It's a subjective question, it would work either way.
Personally I would go with sessions as it doesn't interfere with the URL so people can bookmark the url if they wanted.
However the argument for that would be if they bookmarked it they might see different things if it was done using $_SESSION.