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
Related
My website's webpages displays webpages by using GET to retrieve variables from a predefined URL.
For example the code on the first page: index.php
<p>next page</p>
The second page: blank.php?name1=value1&name2=value2
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo $name1 ;
echo $name2 ;
This way webpages are created on the spot and displayed kind of like a CMS and Iuse this method for all the webpages my site has, but if a user bookmarks a tab they will have out of date information for that webpage because that page content is contained in the URL.
EDIT: If I were to use post would their be a better way of conveying that information to the new webpage? instead of:
<form method="post" action="blank.php">
<input type="hidden" name="name1" value="value1">
<input type="submit">
</form>
Quick and dirty solution: Add a timestamp parameter to your urls, like:
<p>next page</p>
Then, on the page, check if the timestamp is older then a certain duration:
if(!isset($_GET['time']) || time() - intval($_GET['time']) > 60*60) {
header('Location: index.php');
}
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo htmlspecialchars($name1);
echo htmlspecialchars($name2);
So if a link is older than one hour (60 seconds times 60 minutes), it is redirected to the home page!
But this method is not very user friendly! You should better try to build your links so they never get old content when visiting!
You could prevent the user from using the keyboard shortcut for bookmarking, but I don't think there is anyway to prevent the user from bookmarking it in their browser (or writing down the URL for that matter).
You may want to look into generating the data on the page on each page load so if the user bookmarks the URL, they see the most recent information. Or if the user didn't follow a certain path to arrive at that path display a message telling them the data is out of date.
Using POST instead of GET Would resolve the issue for the most part, but I understand this may not be possible depending on the amount of code that you have already created. Another possible solution is to set Session variables to determine if that person should have access to this page or not. If they do not have access, than you send them back their landing page, profile, or even login page. I have done this by placing session variables that can only be set on one page, and then destroyed after the page is viewed, this way they cannot simply go back to the page because the session value is gone.
Sadly it is not possible to prevent people from creating bookmarks to your page, you simply need to filter out who can see(edit or access) it.
You are essentially talking about user sessions only during which all the variables would make sense. Even using POST doesn't solve the problem. In the extreme case one can make a POST request (or search engine may do) and misinterpret the retrieved result. I would suggest to append a sessionid as many other websites do and on the backend to control the valid timeframe. This way you have better control of your website functionality and user experience. Whether a session has expired or not should depend on your business logic, not GET/POST methods.
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
I want to implement a system where I want to know where a POST request cam from.
For example: I have a form with a submit button in it. When the User clicks on the submit button it goes to the page. But I want to know the source from where the post request came.
This is the code till now:
<form action="profile.php?id=<?php echo $user->id; ?>" method="post" name="formAdd"><input name="btnAddUser" type="submit" value="Add User"></form>
Should I use a hidden input element? Would that be a good way OR maybe something else?
First of all, there is no reliable way - users can tamper with requests if they want to.
Besides that, there are two ways to get the kind of information you want:
The referer, available via $_SERVER['HTTP_REFERER']: It contains the full URL from which the request came, but some people use extensions/firewalls/etc. that block or even spoof referers
As you suggested, a hidden form element. This always works unless the user actively wants to tamper with the data sent. So that's the preferred way.
The $_SERVER['HTTP_REFERER'] will let you know where the request came from.
More info:
http://php.net/manual/en/reserved.variables.server.php
It really depends on how secure and reliable you need it to be. A hidden form field would work although it means you'd need to add it to every form that points to your processing script. It's also easy to fake if someone wanted to. Alternatively you could use $_SERVER['HTTP_REFERER']. This isn't always reliable - I believe it does depend on what browser you're using but should be good enough in most simple scenarios. Another alternative would be to store something in the session and use that. That's probably the most secure as it's all server-side and can't be tampered with, but it is probably the hardest to implement (not that it's rocket science).
You could save the page in a session variable ($_SESSION["something"] = "page.php"), that is the most secure way, I think, because a hidden input in a form could be changed by the user, and $_SERVER['HTTP_REFERER'] is not always avaliable.
I would use a hidden field where the value="name_of_referring_page".
This way, no matter what the user's settings, firewall, browser, etc you get the info that you want.
i've a jquery script which post/get data to .php script. but i wanna prevent direct access to the php script. for example if the user look at the html source code,they will be able to access the php script directly by copying the url from the js file and i dont want that. how do i prevent users from doing that?? i want the user to use it via the html UI. i've google but found no link on this. however, i did notice that some popular websites are able to do that. how should i go about doing this??
It seems like a simple redirect is what you're looking for here.
Add something like this to the top of your php file. This will prevent the page from being accessed if the proper post has not been made. Of course you'll have to change the post and redirect to content more relevant to your project.
if (!isset($_POST['data'])) {
header('Location: your-redirect-location');
}
You may also be able to redirect based on the $_SERVER['HTTP_REFERER'] variable.
EDIT: I was going to explain this in a comment but it's too long. I should note that this is a simple solution. It will keep people from accidentally accessing your script. It's really difficult to create a 100% secure solution for your issue, and if somebody really wants to access it, they will be able to. If you don't have anything secure in the script in question, this will be fine. Otherwise, you'll have to look for an alternative.
Here is one solution:
<?php
if(isset($_POST["post_var]))
{
//to the code you want to do when the post is made
}
else
{
//do what you want to do when the user views the post page
}
?>
how do i prevent users from doing that?
You can't - all you can do is mitigate the risk people can fiddle with your script. Making sure you have the right HTTP_REFERER and/or POST data are both useful in that regard: a "malicious" user would need more than pointing her browser to the URL.
More techniques can be used here:
using session variables: you might not want users that are not logged in - if applicable - to use the URL.
using a one-time challenge (token): you can place a value in the HTML page and have the JS code send this value along with the POST request. You store this value in the session when it is generated. Checking the POSTed token against the session token guarantees the user has at least "seen" the HTML page before submitting data - this can also be useful to prevent duplicate submissions.
However, remember that anything a browser can do, people can do it as well. All these techniques can prevent the curious from doing harm, but not the malicious.
All you can do is making sure nobody can really harm you, and in this regard, your Ajax URL is no different than any other URL of your site: if it's publicly reachable, it has to be secured using whatever technique you already use elsewhere - sessions, user rights, etc.
After all, why should you care that users use this URL not using a browser ? You might want to think of it in terms of an API call that, incidentally, your page happens to use.
Your problem is similar to and has the same problems as a cross site request forgery.
To reduce your risk, you can check the request method, check the referrer, and check the origin if set. The best way is to have a secret token that was generated on the server that the client transmits back in every request. Since you're dealing with friendly users who have access to your live code, they may be able to debug the script and find the value, but it would only be for one session and would be a real hassle.
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.