I wanted to transfer value from 1 page to another or in another meaning, available to all page, I tried using global, it doesn't seems to work, I know I can use $_SESSION, but my superior asks me not to use $_SESSION as it may not work on some phone. I need to implement function that enables that variable that holds the value available in all page.
My page process:
Choose a prize > enter email (The values keeps into variable from here) > goes through database checking and so on (cannot change anything here as this stage is a secure page, it is prohibitive to edit anything to prevent any security issues > thanks page (The value will be used here)
Sorry, I can't post any code here as it is secret. I am really sorry about it.
I have tried using GLOBAL, $_GET and $_REQUEST, so are there any methods I can use?
If you're using COOKIEs, you can absolutely use sessions. Session ID's, by default are stored in a cookie on the browser. If for some reason the browser doesn't support cookies, you can still use the query string to transfer the session ID, but there are some security concerns around that (such as session hijacking).
By default, I believe PHP will always try to use a COOKIE for the session ID.
To enable URL-based session IDs, take a look at the PHP.INI option use_trans_sid:
http://www.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid
If you really can't use sessions, your only other options would really be to use $_GET or $_POST.
Using $_POST would require you to have everything wrapped around a <FORM> tag and submit that form for every action on your site.
Using $_GET would require you to append a query string on the URL for every link / action on the site. You will be limited on the amount of data you can store a query string, though.
You could do it with a cookie... in jquery:
$.cookie('some_key','some_value');
or in vanilla javascript:
somekey = 'some_key'l
someval = 'some_val';
document.cookie=somekey+'='+someval;
and get to it in php
<?php
echo $_COOKIE["some_key"];
?>
it's going to be tough not having any code but to answer your question, you have 4 choices, get, post session and cookies. if your superiors dont want you using sessions, then i doubt they want cookies (sessions TYPICALLY USE cookies). I would seriously talk to your boss about using get and post variables because if your trying to keep it secure then passing a post/get variable is very insecure and can be altered in between steps. Session variables can not be.
what I would also check if you are trying to use a post variable is that the secured page in the middle has a form with the value as a hidden field otherwise it will be lost going to the third page because post values are only submitted as part of a form
Related
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.
Here's essentially what I'm trying to accomplish. I have an HTML form which is processed by PHP. A user is required to be authenticated to be able to submit this form. However, I do not want the user to loose their work if the session times out while they are working on filling it out.
My thought process is, when I perform my authentication check, if it fails, the authentication module can store the $_POST data in the $_SESSION array, and redirect the user to the login page. Once the user logs in, the login page can redirect the user back to the submission page, and the authentication module would then see that there is saved $_POST data in the $_SESSION array, and set the $_POST array back to the values that were stored in $_SESSION. Then the submission page can process the form data as normal.
I have done testing and verified that it is, in fact (at least in the version of PHP I'm using), possible to overwrite the value of the $_POST superglobal in PHP. And, in this particular situation, it seems to make a lot of sense to do so. Using this method, no other site code anywhere, other than in the authentication module, would have to be modified for every form on the whole site to take advantage of the "saved post data" feature.
So, I've asked myself if I could do this, and the answer is yes. But should I? Or are there potential problems with using this method? Part of me says it make a lot of sense, but another part of me worries it might be bad code design. If I shouldn't do this, what would be the proper way?
Thanks to all the comments. I ended up using the following code placed in a common library file used by all pages. The only downside is you do have to remember to use global $post in any function or method using the special POST data. But it has the advantage of not being hackish like my previous idea.
if (isset($_SESSION['authSavedPost'])){
$post = $_SESSION['authSavedPost'];
unset($_SESSION['authSavedPost']); // So we don't try to re-post the same data twice
}
else{
$post = $_POST;
}
The authentication check function used on this and other forms, if it fails, will save the current POST data as $_SESSION['authSavedPost'] = $_POST so it can later be restored by the above code.
I'm using a 3rd party app that I need to integrate with my own app. In the 3rd party app, information is posted via a form and then re-directed to my site for further processing. The re-direct to my site will contain variables that I'll need from the form within the re-direct URL. However, I don't want the user who published the form to be able to view those variables.
If the re-direct link is hidden on the 3rd party app (i.e. it's not in the form), then one method that I thought which could work would be to direct the 3rd party app to a "pre-processing" script which does the following:
session_start();
$_SESSION['some_variable_to_save'] = $_GET['some_variable_to_save']; //properly sanitized!!
header('Location: where_i_really_want_to_process.php');
exit;
Then, in where_i_really_want_to_process.php I can process the session variables. Is this a secure method to ensure that the user never sees the $_GET variables?
Your suggestion of using $_SESSION seems to be the only solution.
However to make life a little easier and to cope with any changes that may occur just put the whole $_GET array onto a Session variable
session_start();
// dont sanitization here, do it in the where_i_really_want_to_process.php
$_SESSION['previous_GET'] = $_GET;
header('Location: where_i_really_want_to_process.php');
exit;
It is physically impossible to "ensure" the user never "sees" some form of the data being passed if you have to have the user forward the data to you. They must see some form of the data, otherwise they can't turn around and tell your server what the data was.
If you could encrypt the data, that would effectively hide the data from the user (assuming you use good encryption). But you lack control of the third party, so this may not be viable.
Another option would be to find a third party you can trust to give limited db access, and have them contact your server directly instead of using the client as a middleman. Without knowing exactly what you're doing, I have no idea if this is viable.
If all you're doing is trying to protect "normies" from bookmarking the GET values, the shove-into-session-then-redirect trick is plenty. Only other option would be to write something js/ajax/whatever that does it client side- however that's less transparent to the user than doing it serverside, as well as depends on the user not blocking your method of hand-waving. Very very few people disable internal redirects.
I do endorse Riggs's method (shove all of $_GET into session instead of just the current key you want) over the solution in-question, however, as it lets you pretty much ignore this helper script for the life of the application.
Try to use an associative array of variables $_POST:
$_POST = $_GET;
$_GET = [];
header('Location: where_i_really_want_to_process.php');
Well, I just started to work on server side scripting , I chose PHP, So let me explain where Im getting troubled.
This is very a quite simple questions.See, I have some links like these on my page1.php
profile
photos
Now when user jumps to page2.php or page3.php, I also want to pass the user unique ID to the corresponding page, say his email.so that i can update the page2.php according to the username.
When I googled, I heard lots of contradictions , some people were explaining to use session_start() and some people explains cookies and some people says POST and GETmethods. Some people said its easy to hack when you use GET or POST method and some people answered Cookies are client side and it disconnects from server and after hearing all those I decided to use session_start()
But as im a newbee I dont know what to chose,which is the best way.Could anyone kindly explain me which is the best solution to use and why? and also please provide some sample example so that i can understand it much better.Any help is greatly appreciated.Thanks
In order of preference as a solution for the problem you have presented in your question.
Sessions
As this is details of the current user the easiest way to complete this is to use PHPs sessions. This will allow you to access the details in a super global array called $_SESSION DOCs from any page that calls the session_start() DOCs function. This should appear before any output is sent to the browser so it is usually put at the very top of the PHP script.
Each user has their own session on the server and session_start() automagically provides your script with the right data for the current user.
page1.php
session_start();
$users_email_address = 'example#example.org'; // source from DB or whatever
$_SESSION['email_address'] = $users_email_address;
page2.php and/or page3.php
session_start();
echo $_SESSION['email_address'];
Please see the manual documentation for session_start() for more examples.
Use HTTP GET parameters
This works best for URLs that you may want to share - so search results pages or perhaps pagination.
Passing user details in this manner is not ideal as the user can easily change the URL in the browsers address bar. So they could change their email address to someone elses and fool your script.
Using cookies
Storing user data in cookies is not a brilliant idea as a user is able to edit cookies as they are stored on their machine.
Also cookies have a size limit of 4KB and get sent with every request header to the server - thus slowing your site down.
Using HTTP POST parameters
This the very least recommended method for doing this. POST is intended for receiving data to save it on the server and not for navigation. If the user were to press back on page3.php then they would be shown a "do you want to resumbit this form" message by their browser. Pretty unintuitive for a user who thought that they had just clicked a link and not submitted a form.
Best practice is to use session variables ( such as $_SESSION['variable_name']; ).
If you involve form submission, use POST method.
If you only get simple information by setting up parameters, use GET method.
You can use either of those.
Session
This is the best as the email address is stored in the server side. There is no way someone can get hold of the value and try to do bad things with it.
GET
Although this achives what you want by appending to the URL like page2.php?email=someone#example.com, it's easily readable in the browser address bar. It's like you don't store this value anywhere, just pass it between pages.
POST
This is similar to GET but that the parameter gets passed under the hoods. The user can still find this out if he uses plugins to his browser. Like GET, here also the value isn't really stored anywhere. To do a POST, however, you'll need to have a form on your page. Think of it like a form where you ask the user to input his email address.
<form action="page2.php" method="post">
<input type="text" name="email"/>
</form>
In the above example, you can read the value of email in page2.php by doing $_POST["email"].
Note that if you change the method to get, it becomes same as a GET request.
<form action="page2.php" method="get">
<input type="text" name="email"/>
</form>
Here, you can read the value of email in page2.php by doing $_GET["email"].
COOKIES
This works by storing a value on the user's browser. The least recommended of all approaches as the user need not have his cookies feature turned on by default.
Just complementing the answer of Treffynnon:
actually page2.php should be page1.php
Manual about session:
http://www.php.net/manual/pt_BR/function.session-start.php
session_start() must come before all html code or echo in php. In other words: before everything that generate html's code.
sessions are the best choice .Because sessions were one solution invented to over come the
STATELESS nature of the web pages .
sessions are very simple to understand and use . each user will be having an session .
When the user id is set you want to add it to a session. A session is basically a variable that is available over all your pages.
When you set your sessions you want to have session_start(); at the very top of your page. It needs to be before the <html> tag.
Set your session like so $_SESSION['user_id'] = 1;
You can then recall the value of the session on any page like this echo 'User id: ' . $_SESSION['user_id'];
This will output: User id: 1
There's a lot of info in the manual - http://www.php.net/manual/en/book.session.php
I'm making a register page, signup.php, and basically what I want it to do is check for errors and if there are none, redirect to register.php. That is fine and whatnot, but register.php is the page where the actual account is made (e.g. mySQL query). Of course, in order to do that, I actually need the params gathered form signup.php. I was wondering if I could do something like this..
header("Location: register.php, TYPE: POST, PARAMS: {user,pass,email}")
Obviously I can not use $_GET as I am transmitting sensitive data (e.g. passwords).
Any ideas/suggestions?
EDIT: Thank you all for your answers. I am now storing the parameters in a $_SESSION variable.
I see no point in such redirect.
Why not to post right away to register.php?
And then check for errors and save data in database in the same register.php?
without any redirects
No, you can't, and such data would be just as insecure to any determined attacker.
Store the data in a session variable for use in the next page.
Even if this is possible, you will hit another brick wall - the implementation of redirects in the popular browsers. While the standard requires, that it asks the user if a post is redirected, all popular browsers simply interpret the redirect as a GET. In short: you can't redirect a POST that way, you'll have to find another way without a round trip to the client, or use GET.
Also, you should be aware that unless your requests are done via https, both GET and POST will present the sensitive information to any listener, as POST simply buts the query string into the http request and not the url. Security wise, both are the same.
You could store them in the $_SESSION and refer to those in the register.php page, doing some checking to make sure someone has actually filled out the information and didn't just navigate to it.