When the use of GET method is justified? - php

When the use of GET method is justified? Is it OK to always use POST? Is it right that GET is transferred fast then POST?

The GET verb is used in Requests that are idempotent, e.g. when they lead to the same result (and have no observable side-effects on the returned resource). So, you use them for retrieval of a resource only.
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.
and also
1.3 Quick Checklist for Choosing HTTP GET or POST
Use GET if:
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.
However, before the final decision to use HTTP GET or POST, please also consider considerations for sensitive data and practical considerations.
See
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html and
http://www.w3.org/2001/tag/doc/whenToUseGet-20040321
That second link explains the difference pretty well.
Note that there is not just GET and POST in the HTTP protocol, but a couple of other verbs, like PUT, HEAD, DELETE, etc as well. Those play a large role in RESTful applications.

Short answer:
Use GET requests when it makes sense for the user to be able bookmark the request, share the request, and come back to over and over again. It makes sense to be able to bookmark the result of a Google query, for example.
Longer answer:
Use GET requests when the user is simply fetching/viewing a resource, and doesn't have any significant side-effects on your website's data or on future requests. If the request is creating, modifying, or deleting something, it should be a POST. If the user is logging in to a website, that has effects on future requests, so it should be a POST, not a GET.
Note: Users can still change POST variables.
It's easier to for the user to change query string (GET) values, but it's not too difficult for the user to change POST values. Your website's security should take this into account! Using POST for security isn't really a valid reason, except for the fact that POST variables aren't part of the URL and aren't bookmarked, while GET variables are. This prevents users from accidentally sharing things like passwords when sharing links.

You use post for larger amounts of data, or data that you don't want to appear within the url. For instance, you don't want the url to delete a page, or create one, to appear in someones history. Neither do you want to save passwords in this way.
For search strings and such, you can easily use get. It allows users to copy a specific url, like a specific search reasult, or a link to the 5th page in a paginated list.
So, either are ok for their own purposes. The only thing you should remember is the maximum size of 8Kb for an url, including the get parameters.

GET is better for things that should be able to be bookmarked, and simple queries with few, short parameters.
POST is better for sensitive fields that the user shouldn't see, for large binary transfers, and for transfers with many fields or very long fields.

Generally, GET is preferred for search pages (like on google) and something which is not sensitive like username or password should not be shown in urls.
Consider Security Too:
You should be very selective when using GET for example if you end up coding like this:
$page = $_GET['page'];
include $page . '.php';
A bad guy can visit a url like:
http://www.yourdomain.com?page=../../../etc.pwd
Or if you do:
$id = $_GET['id'];
mysql_query('delete from table where id = $id');
A bad guy can delete all your records from db just by visiting:
http://www.yourdomain.com?id=5
http://www.yourdomain.com?id=10
There do exists solution to those mistakes however but still you should be selective when choosing between POST and GET.

Related

Why is id variable not passed to this file? [duplicate]

What's the difference when using GET or POST method? Which one is more secure? What are (dis)advantages of each of them?
(similar question)
It's not a matter of security. The HTTP protocol defines GET-type requests as being idempotent, while POSTs may have side effects. In plain English, that means that GET is used for viewing something, without changing it, while POST is used for changing something. For example, a search page should use GET, while a form that changes your password should use POST.
Also, note that PHP confuses the concepts a bit. A POST request gets input from the query string and through the request body. A GET request just gets input from the query string. So a POST request is a superset of a GET request; you can use $_GET in a POST request, and it may even make sense to have parameters with the same name in $_POST and $_GET that mean different things.
For example, let's say you have a form for editing an article. The article-id may be in the query string (and, so, available through $_GET['id']), but let's say that you want to change the article-id. The new id may then be present in the request body ($_POST['id']). OK, perhaps that's not the best example, but I hope it illustrates the difference between the two.
When the user enters information in a form and clicks Submit , there are two ways the information can be sent from the browser to the server: in the URL, or within the body of the HTTP request.
The GET method, which was used in the example earlier, appends name/value pairs to the URL. Unfortunately, the length of a URL is limited, so this method only works if there are only a few parameters. The URL could be truncated if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser not the best place for a password to be displayed.
The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output. It is also more secure.
The best answer was the first one.
You are using:
GET when you want to retrieve data (GET DATA).
POST when you want to send data (POST DATA).
There are two common "security" implications to using GET. Since data appears in the URL string its possible someone looking over your shoulder at Address Bar/URL may be able to view something they should not be privy to such as a session cookie that could potentially be used to hijack your session. Keep in mind everyone has camera phones.
The other security implication of GET has to do with GET variables being logged to most web servers access log as part of the requesting URL. Depending on the situation, regulatory climate and general sensitivity of the data this can potentially raise concerns.
Some clients/firewalls/IDS systems may frown upon GET requests containing an excessive amount of data and may therefore provide unreliable results.
POST supports advanced functionality such as support for multi-part binary input used for file uploads to web servers.
POST requires a content-length header which may increase the complexity of an application specific client implementation as the size of data submitted must be known in advance preventing a client request from being formed in an exclusively single-pass incremental mode. Perhaps a minor issue for those choosing to abuse HTTP by using it as an RPC (Remote Procedure Call) transport.
Others have already done a good job in covering the semantic differences and the "when" part of this question.
I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.
You should use POST if there is a lot of data, or sort-of sensitive information (really sensitive stuff needs a secure connection as well).
Use GET if you want people to be able to bookmark your page, because all the data is included with the bookmark.
Just be careful of people hitting REFRESH with the GET method, because the data will be sent again every time without warning the user (POST sometimes warns the user about resending data).
This W3C document explains the use of HTTP GET and POST.
I think it is an authoritative source.
The summary is (section 1.3 of the document):
Use GET if the interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the
user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.
Get and Post methods have nothing to do with the server technology you are using, it works the same in php, asp.net or ruby. GET and POST are part of HTTP protocol.
As mark noted, POST is more secure. POST forms are also not cached by the browser.
POST is also used to transfer large quantities of data.
The reason for using POST when making changes to data:
A web accelerator like Google Web Accelerator will click all (GET) links on a page and cache them. This is very bad if the links make changes to things.
A browser caches GET requests so even if the user clicks the link it may not send a request to the server to execute the change.
To protect your site/application against CSRF you must use POST. To completely secure your app you must then also generate a unique identifier on the server and send that along in the request.
Also, don't put sensitive information in the query string (only option with GET) because it shows up in the address bar, bookmarks and server logs.
Hopefully this explains why people say POST is 'secure'. If you are transmitting sensitive data you must use SSL.
GET and POST are HTTP methods which can achieve similar goals
GET is basically for just getting (retrieving) data, A GET should not have a body, so aside from cookies, the only place to pass info is in the URL and URLs are limited in length , GET is less secure compared to POST because data sent is part of the URL
Never use GET when sending passwords, credit card or other sensitive information!, Data is visible to everyone in the URL, Can be cached data .
GET is harmless when we are reloading or calling back button, it will be book marked, parameters remain in browser history, only ASCII characters allowed.
POST may involve anything, like storing or updating data, or ordering a product, or sending e-mail. POST method has a body.
POST method is secured for passing sensitive and confidential information to server it will not visible in query parameters in URL and parameters are not saved in browser history. There are no restrictions on data length. When we are reloading the browser should alert the user that the data are about to be re-submitted. POST method cannot be bookmarked
All or perhaps most of the answers in this question and in other questions on SO relating to GET and POST are misguided. They are technically correct and they explain the standards correctly, but in practice it's completely different. Let me explain:
GET is considered to be idempotent, but it doesn't have to be. You can pass parameters in a GET to a server script that makes permanent changes to data. Conversely, POST is considered not idempotent, but you can POST to a script that makes no changes to the server. So this is a false dichotomy and irrelevant in practice.
Further, it is a mistake to say that GET cannot harm anything if reloaded - of course it can if the script it calls and the parameters it passes are making a permanent change (like deleting data for example). And so can POST!
Now, we know that POST is (by far) more secure because it doesn't expose the parameters being passed, and it is not cached. Plus you can pass more data with POST and it also gives you a clean, non-confusing URL. And it does everything that GET can do. So it is simply better. At least in production.
So in practice, when should you use GET vs. POST? I use GET during development so I can see and tweak the parameters I am passing. I use it to quickly try different values (to test conditions for example) or even different parameters. I can do that without having to build a form and having to modify it if I need a different set of parameters. I simply edit the URL in my browser as needed.
Once development is done, or at least stable, I switch everything to POST.
If you can think of any technical reason that this is incorrect, I would be very happy to learn.
GET method is use to send the less sensitive data whereas POST method is use to send the sensitive data.
Using the POST method you can send large amount of data compared to GET method.
Data sent by GET method is visible in browser header bar whereas data send by POST method is invisible.
Use GET method if you want to retrieve the resources from URL. You could always see the last page if you hit the back button of your browser, and it could be bookmarked, so it is not as secure as POST method.
Use POST method if you want to 'submit' something to the URL. For example you want to create a google account and you may need to fill in all the detailed information, then you hit 'submit' button (POST method is called here), once you submit successfully, and try to hit back button of your browser, you will get error or a new blank form, instead of last page with filled form.
I find this list pretty helpful
GET
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should (almost) never be used when dealing with sensitive data
GET requests have length restrictions
GET requests should be used only to retrieve data
POST
POST requests are not cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
The GET method:
It is used only for sending 256 character date
When using this method, the information can be seen on the browser
It is the default method used by forms
It is not so secured.
The POST method:
It is used for sending unlimited data.
With this method, the information cannot be seen on the browser
You can explicitly mention the POST method
It is more secured than the GET method
It provides more advanced features

How to make sure AJAX is called by JavaScript?

I asked a similar question before, and the answer was simply:
if JavaScript can do it, then any client can do it.
But I still want to find out a way do restrict AJAX calls to JavaScript.
The reason is :
I'm building a web application, when a user clicks on an image, tagged like this:
<img src='src.jpg' data-id='42'/>
JavaScript calls a PHP page like this:
$.ajax("action.php?action=click&id=42");
then action.php inserts rows in database.
But I'm afraid that some users can automate entries that "clicks" all the id's and such, by calling necessary url's, since they are visible in the source code.
How can I prevent such a thing, and make sure it works only on click, and not by calling the url from a browser tab?
p.s.
I think a possible solution would be using encryption, like generate a key on user visit, and call the action page with that key, or hash/md5sum/whatever of it. But I think it can be done without transforming it into a security problem. Am I right ? Moreover, I'm not sure this method is a solution, since I don't know anything about this kind of security, or it's implementation.
I'm not sure there is a 100% secure answer. A combination of a server generated token that is inserted into a hidden form element and anti-automation techniques like limiting the number of requests over a certain time period is the best thing I can come up with.
[EDIT]
Actually a good solution would be to use CAPTCHAS
Your question isn't really "How can I tell AJAX from non-AJAX?" It's "How do I stop someone inflating a score by repeated clicks and ballot stuffing?"
In answer to the question you asked, the answer you quoted was essentially right. There is no reliable way to determine whether a request is being made by AJAX, a particular browser, a CURL session or a guy typing raw HTTP commands into a telnet session. We might see a browser or a script or an app, but all PHP sees is:
GET /resource.html HTTP/1.1
host:www.example.com
If there's some convenience reason for wanting to know whether a request was AJAX, some javascript libraries such as jQuery add an additional HTTP header to AJAX requests that you can look for, or you could manually add a header or include a field to your payload such as AJAX=1. Then you can check for those server side and take whatever action you think should be made for an AJAX request.
Of course there's nothing stopping me using CURL to make the same request with the right headers set to make the server think it's an AJAX request. You should therefore only use such tricks where whether or not the request was AJAX is of interest so you can format the response properly (send a HTML page if it's not AJAX, or JSON if it is). The security of your application can't rely on such tricks, and if the design of your application requires the ability to tell AJAX from non-AJAX for security or reliability reasons then you need to rethink the design of your application.
In answer to what you're actually trying to achieve, there are a couple of approaches. None are completely reliable, though. The first approach is to deposit a cookie on the user's machine on first click, and to ignore any subsequent requests from that user agent if the cookie is in any subsequent requests. It's a fairly simple, lightweight approach, but it's also easily defeated by simply deleting the cookie, or refusing to accept it in the first place.
Alternatively, when the user makes the AJAX request, you can record some information about the requesting user agent along with the fact that a click was submitted. You can, for example store a hash (stored with something stronger than MD5!) of the client's IP and user agent string, along with a timestamp for the click. If you see a lot of the same hash, along with closely grouped timestamps, then there's possibly abuse being attempted. Again, this trick isn't 100% reliable because user agents can see any string they want as their user agent string.
Use post method instead of get.Read the documentation here http://api.jquery.com/jQuery.post/ to learn how to use post method in jquery
You could, for example, implement a check if the request is really done with AJAX, and not by just calling the URL.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Yay, it is ajax!
} else {
// no AJAX, man..
}
This solution may need more reflexion but might do the trick
You could use tokens as stated in Slicedpan's answer. When serving your page, you would generate uuids for each images and store them in session / database.
Then serve your html as
<img src='src.jpg' data-id='42' data-uuid='uuidgenerated'/>
Your ajax request would become
$.ajax("action.php?action=click&uuid=uuidgenerated");
Then on php side, check for the uuid in your memory/database, and allow or not the transaction. (You can also check for custom headers sent on ajax as stated in other responses)
You would also need to purge uuids, on token lifetime, on window unload, on session expired...
This method won't allow you to know if the request comes from an xhr but you'll be able to limit their number.

Send hidden variable when clicking hyperlink, secure sql

I wanted to pass a hidden variable at first with $_POST but i have come to realize that users can change $_POST almost as easily as $_GET. Is it possible to somehow restrict this ability or is there another way to do this? Also, it doesnt seem you can use $_POST in this simple example below?:
index.php
<view recipe
test.php
$variable = $_GET['variable'];
$query = $database->query("SELECT name, description, date_added from recipe where recipe_id = $variable");
(EDIT: i do check that the input is indeed an integer although i skipped this above to minimize the code of the example. I should've made this clear earlier).
I guess the only borderline "malicious" things a user could do here is loop through the recipe_id:s to find out how many recipes were in the database or even the first recipe added just by changing the $variable. Not that i care in this particular case, but im sure i will when it comes to other examples. I realize that i want to make the information available, i just want it to go through the "proper channels" i guess. Is this just the way things are or am i missing something vital?
People always write things like "validate your input". And i agree with that. But in this case its just one integer the user "inputs". What can be done besides that validation? Again, im slowly progressing/learning this so please be patient if i seem to make simple mistakes.
(Using PHP, PDO, Mysql)
Thank you!
It's all about HTTP requests. The browser communicates with the server through HTTP requests. These are entirely transparent to the user however you look at it. Open the Web Inspector in your browser (or Firebug, or Fiddler or whatever else) and inspect the raw HTTP requests, live. Anyone can send these requests to your server anytime, containing any data at all.
Understand this concept, it is important. There's no such thing as "secret" information in the communication between your server and the client (from the POV of the client). You do not control the input to your server. Neither can you "hide" any data that is going from the client to your server.
An HTTP request represents a, well, request for data or for some action. The server should, well, serve the request to the best of its abilities. If a request is invalid, the server must reject it. The server should judge the validity of each request independently of every other request, it should be stateless. The server cannot presume the validity of any request without validating it. It should only ever output information which is not security sensitive and treat all incoming data as suspicious. That's the fact of life.
The "variable" isn't restricted to be an integer at all in your code. An evil user could probably change the value of "variable" to "';truncate recipe;--". Execute this and whoops ... all recipes are gone.
always ensure that you use proper validation. search the interwebs for "sql injection" and have a look at functions like mysql_real_escape_string (and it's documentation).
If you don't want users to see an incremental recipe ID that they can easily modify, then generate a unique random string to use to identify recipes. This will stop users from being able to play with the recipe ID in the GET or POST data.
They can still modify it but they will need to obtain the random string in order to pull out a recipe.
The content of request fields, whether $_POST or $_GET, is not typed. It is just plain strings, which means that it's pretty much "open game" on the client side. It's the very reason we keep repeating that client input cannot be trusted, and must be validated on the server side.
Regarding your second question: recall that $_GET will contain the result of a form using the get method, while $_POST will contain data from post method forms. $_GET purpose is to contain url parameters, if they exist (to be precise, a get method form will pass all its parameters via the url).
On a side note, I should also tell you that you shouldn't use one verb for another, each one as a specific purpose. The get method is about getting data, not updating it, while post, put, delete are about updating data. This means that your example is following these rules, and should not try to use a post form instead (although this is technically feasible, you would just need to replace your link tags with forms).
see the HTTP specs on this matter.
you may create a session based permission system that:
when user visited your site, and his/her browser rendered the link, in that php, you set a session variable for that link,
$_SESSION["permitted_recipe_id"] = $row['recipe_id'];
Now you know exacly what recipe id that user can click,
with this check:
$variable = $_GET['variable'];
if($variable != #$_SESSION["permitted_recipe_id"]){
exit("error you do not access to this result");
}
$query = $database->query("SELECT name, description, date_added from recipe where recipe_id = $variable");
This will ensure that user visited the page before it send a request. This solution will prevent consecutive POST requests to fetch all website data,
if you show multiple links that user can click, you must implement $_SESSION["permitted_recipe_id"] as an array containing all ids' that send to user as links.
but beware, multi tab experiences may create bugs for this solution. This is the idea, you have to carefully work it out for a relase enviroment solution.

How to protect from malicious use of jQuery post handler?

I use jquery POST calls to fetch data to display in various sections of my websites.
Usually, they POST to a single 'ajax_handler.php' page which reads the requested parameters and returns the relevant data. Typical parameters might be 'get_order_details',123
How could I stop users posting to the script to try and retrieve data which they should not be able to? I know I can verify that data belongs to the currently logged in user, for instance, but how could I stop users 'guessing' that there might be a handler for 'get_some_info'?
Since users could even run javascript straight from the URL this seems to be a major security problem to me as the client would have access to SESSION and COOKIE data (which I would otherwise use for security).
I guess I could start by naming each of my handler identifiers with a random string, but I'd prefer not to compromise the legibility of my code.
Naming your handlers with a random string is security through obscurity and while it might slow someone down, it won't stop them.
The best thing to do is to store a session or database checksum each time a page is accessed. Then also send that same checksum along with the POST content. When the form is submitted, through AJAX or otherwise, you compare the checksums. If they don't match then you know the user wasn't on the appropriate page and is trying to access the handler through some other method.
For each user, you can store within your database which data he should be able to view and which he shouldn't. Each time you get a request, e.g get_order_details, you should call a function which does your security checking to make sure both that the user is logged in, and that he has access to the 'get_order_details' method or any other method he is trying to access.
What you're trying to do is fundamentally antithetical to how the Internet works. You can't and shouldn't attempt to limit the way users make requests to your services. This is an extremely outdated and backwards way of thinking. Instead of trying to limit the ways in which users can use your service, be thankful that they're using your service in the first place.
All you can do is make sure that the user is authenticated and has access to the record they're requesting. If you're using a system which has no authentication, and you want to prevent users from "guessing" the ID of the next record, don't use sequential IDs. Use randomly generated strings as your identifier. Make them sufficiently long that it will be difficult for users to stumble upon other records.

What is the "?" symbol in URL used for in php?

I am new to PHP. In the path of learning PHP language, I notice that, some website would this kind of URL:
www.website.com/profile.php?user=roa3&...
My questions:
What is the "?" symbol used for?
If I were develop a php website, must I use it in my URL? For example, after a user(roa3) successful logged in, I will redirect to "www.website.com/profile.php?user=roa3" instead of "www.website.com/profile.php"
What are the advantages and disadvantages of using it?
Good questions, briefly,
"?" stands for the start of querying
string which contains the data to be
passed to the server. in this case
you are passing user=roa3 to
profile.php page. You can get the
data by using $_GET['user'] within
profile.php. querystring is one of the methods to send data to the server from client agent. The other one places the data in HTTP body and POST to the server, you don't see the HTTP POST data directly from browser.
querystring can be edited by user
and it is visible to the public. If
www.website.com/profile.php?user=roa3
is intended to be public then it is
fine, otherwise you may want to use
session to get current user's
context.
it is a flexible way to pass data to
the server, but it is visible and
editable to the users, for some
sensitive data, at least produce
some kind of hash before attaching
it to the querystring, this prevents
users to edit it or understanding
the meaning of it. However this
doesn't prevent a decent hacker to
do something wrong about your
website. Different browsers support different max length of URL, the lengthy URL is made up by those querystring parameters. If you want to send large amount of data, place the data in the HTTP body and POST to the server.
Most of the answers I've seen so far have been in terms of PHP, when in reality this isn't language specific. The answers given so far have been from the view of PHP and the methods you would use to access the information differ from one language to the next, but the format in which the data is in the URL (known as the Query String) will remain the same (Ex: page.ext?key1=value&key2=value&...).
I don't know your technical background or knowledge, so please forgive me...
There are two different methods for a web page to provide data back to the web server. These are known as the POST or GET methods. There also also a bunch of others, but none of those should be used in any sort of web design when dealing with a normal user. The POST method is sent invisibly to the server and is meant for 'uploading' data, while the GET method is visible to the user as the Query String in the URL and is only meant to literally 'get' information.
Not all sites follow this rule of thumb, but there can be reasons as to why. For example, a site could use POST exclusively to get around caching by proxy servers or your browser, or because they use double byte languages and can cause issues when trying to perform a GET because of the encoding conversion.
Some resources about the two methods and when to use them...
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://weblogs.asp.net/mschwarz/archive/2006/12/04/post-vs-get.aspx
http://en.wikipedia.org/wiki/Query_string
Now from a strictly PHP position, there are now 3 different arrays you can use to get the information a webpage has sent back to the server. You have to your disposal...
$_POST['keyname'], to grab only the information from a POST method
$_GET['keyname'], to grab only the information from a GET method
$_REQUEST['keyname'], to allow you to grab the POST, GET, and any COOKIE information that might have been submitted. Sort of a catchall, especially in cases where you don't know which method a page might be using to submit data.
Don't get sloppy by going directly with the $_REQUEST method. Unless you have a case like I mentioned above for the $_REQUEST variable, then don't use it. You want to try and use a 'deny all, and only allow x,y,z' approach when it comes to security. Only look for the data that you know your own site will be sending, only look for the combinations that you'll be expecting, and cleanse all of the information before you use it. For example..
Never do an eval() on anything passed via the above methods. I've never seen this done, but it doesn't mean people haven't tried or do.
Never use the information directly with databases without cleaning them (research into SQL injection attacks if you're not familiar with them)
This is by far not the end-all, be-all to PHP security, but we're not here for that. If you want to know more along line, well then thats another question for SO.
Hope this helps and feel free to ask any questions.
1) If a user logs in to your site, you would use Sessions to store there username instead of passing it in the url e.g profile.php?username=roa3
2) Using a ? symbol in the urls is generally considered bad for Search Engine Optimization. Also, the urls look a bit ugly. Using mod_rewrite you can do the same thing as profile.php?user=roa3 or products.php?id=123&category=toys with: site.com/profile/roa3 or products/toys/123.
Using the CodeIgniter framework will give you friendly URLs by default and eliminate the need for ?s in your urls. See this page for an example.
3) The ? symbol is also used inside the code of a php page. For example, an if else block such as:
if ($x==1)
$y=2;
else
$y=3;
can also be written as:
$y=($x==1) ? 2 : 3;
The "?" signifies that some GET variables are to follow. You example uses a variable called "user", and assigns a variable called "roa3".
Advantages of using GET variables:
they can be bookmarked as part of the URL
Disadvantages
they are public.. Anyone can intercept and see this information. These url requests are even cached by servers along the journey. So anyone can impersonate your roa3 user just by typing that information in by hand... also they could change the roa3 to a different user and impersonate them..
You can also use a "&" symbol to separate many variables e.g.:
www.website.com/profile.php?user=roa3&fav_colour=blue
Other options:
POST variables
You can send your variables via the POST variables. These variables are passed in the header of the request, not the url of the request. they are not immediately obvious, and are not cached by servers along teh journey, but they can still be read. unless you have a HTTPS conection established.
variables in a form can be sent by POST or GET methods.. You specify this in the "method" of the form. <form action="index.php" method='post'/>
SESSION variables
Session variables are stored on the server. A session id is passed to the user, and this session id is passed back to the server every time the user makes another request. This session id can then be used to get the session variables that were stored. So you could store a user's favorite colour, their name, and ip address etc.. but you could store it on teh server rather than the user's home PC.
Session ids can be impersonated, so it is good to check against the user's IP, and or to wrap them in a secure conection. eg https.
session variables can't be changed by someone who intercepted the request.
COOKIE variable:
Similar to the session variables, except that they are stored on the user's PC, not the server. They are stored against a domain, and when they go to that domain, they resubmit the variables in the header of the request to the server.. this means that the user could change and hack the variables, or someone else could.
To access these variables in php you can use:
$x = $_GET['user'] for a get variable
$x = $_POST['user]
$x = $_REQUEST['user'] - the combination of get, post and cookie variables
$x = $_COOKIE['user'] - cookie variables
$x = $_SESSION['user'] to access the session variables
(user could be replaced with the name of the variable you are using)
Simple enough stuff, but important to know what they actually do.
? is part of the HTTP standard and not part of PHP. Thought I should point that out so when you move on to another language and see it again you are not confused thinking there is PHP involved.
Otherwise there are some excellent answers above.
From the server's point of view, the ? is just another character. PHP provides easy methods for parts of the URL after the ? character, e.g. for "/profile.php?user=roa3", PHP will set $_GET['user'] = 'roa3'.
The reason ? is useful in URLs is that browsers can construct dynamic URLs using forms -- in the case above, I would expect that the URL was built by an HTTP form with a field "user", into which the human user has typed "roa3".
"?" is used to separate the URL and the parameters. For e.g, it is like http://www.url.com/resourcepath?a=b&c=d. In this case a=b is like request_parameter=request_value.
Ya, Its not advisable to use much of the parameters because the total url size is limited and it is like GET request, where all the parameters are shown on the url and the user can modify it. In your example, say what if a user modify the url to "user=techmaddy'.
Advantage is it can be used for the GET kind of requests. Disadvantage is low security, limitation in size.

Categories