Please explain the PHP $_GET request - php

I've never understood this, and on my own projects I have never needed it. But I've been contributing to WordPress a little, and they use it heavily.
Somehow they are able to redirect the user to a different page with some sort of GET variable in the URL (which is what I understand to be the advantage of using GET over POST). How do they do this? Is it as simple as making a header like header('site.com/page.php?foo=true');? This can't be useful since you have to hard code everything in (unless you want to create a string based on other variables which is kind of annoying, even still). I thought there would be a built-in function like send_get('page.php', $foo);.
I understand how to use information by using $foo = $_GET['foo'];, but I don't know how to send it with PHP.
An explanation would be appreciated - thanks!

There isn't exactly a "customary" way of using it. It is one of nine superglobals. The way you use them is at your discretion. As Greg P already mentioned, they are passed through the URL.
I know how to set up a HTML form that sends variables this way, but how can I do the same thing with PHP?
If you're talking about sending GET variables with PHP solely, the answer is no. You needn't even have PHP to send a GET variable. It is as simple as adding a question mark followed by a variable name = something. Separate several of them using an ampersand (&)
Setting up a GET variable is as easy as creating an anchor link.
<a href='somepage.php?getVar1=foo&anotherVariable=2&thirdVar=3
You can use PHP to dynamically place certain information in there instead of writing it manually, which is the entire purpose of the language to begin with. It is a preprocessor
So, something like this should get you started
<?php
$someID = // An id pulled from a mysql_query
echo "<a href='somepage.php?someID=" . $someID . "'>GET LINK</a>";
I thought there would be a built-in function like send_get('page.php', $foo);
Again, PHP is a preprocessor. It doesn't send information, it only outputs it. What you're talking about is Javascript.. moreover, AJAX. AJAX is the only method that will allow you to send GET variables "behind-the-scenes". And, like was mentioned in another post, jQuery has an awesome codebase for this.

I think you're missing the forest for the trees...the $_GET/$_POST are just variables that are passed to the page processing them - what is DONE with them and how it is done, is up to the design of the application. For example, Joomla always puts the component_id and the item_id in the $_GET array, and has been designed with that in mind, so expects them to be there, and constructs the page, or redirects, or whatever with that in mind.
In your example, a send_get() function might be a good idea (I didn't design it), but the architects didn't see it that way for one reason or another. Joomla happens to have a redirect function that does have a certain dependancy on what was passed in the $_GET, but that is only by design of the applications authors.

Maybe redirect URL is kept in some of session variable. Properly $_GET variable, indicate for wordpress: "check session variable for redirect URL".

PHP.net says:
An associative array of variables passed to the current script via the URL parameters.
URL parameters: generally are variables passed to a script via the URL such as in your example site.com/page.php?foo=true. Everything after the ? is considered a paramter.
Quoted from a StackOverflow question:
The HTTP protocol defines GET type requests as being idempotent, while POST may have side effects. In pain 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.

Related

Php, I want to add a parameter for redirections in ALL links, how to do that?

Lets imagine a "language" parameter in every GET request. I must add this parameter to all request. Its OK to just type it in php code, but if I have thousands "header()" calls, what to do? Not mentioned the HTML/Javascript links. Sessions not an option, sorry
How is this different from any other get parameter? If you require it, then your code needs to pass the value around, just as it must pass around any other get parameters that need to be retained and added to other links or Location: headers. If this represents a major logistical issue for you, you might consider the design of your controller system, and overall framework for dealing with requests and url parameters.

jQuery posting variables within the same file

I have some variables set in Javascript. Further down the script I want to use these values in PHP. I realise I need to POST/GET them with jQuery, but I don't understand either function fully, even after looking at the manuals.
Could somebody break it down and explain the parameters?
Would I be better off using GET or POST in the instance?
Can the URL specified be the same as the current page e.g. index.php?
Thanks very much for your help.
You can not do this unless PHP is writing the javascript. PHP is on the server side and will be parsed before Javascript is ever seen by the client. Any variables set by JS will NOT be seen by PHP on the same request.
It's really just a question of style, really.
GET places all key/value-pairs in the URL field, whereas POST puts it in the HTTP body. Since URLs are limited in length, POST is preferred for longer, larger sets of data or data needing to benefit from TLS/SSL encryption.
So let's say we have a key: articleID. You want to pass 1 to articleID, so that the backend can contact the database and retrieve the article in question.
If you make a GET request, you'd invoke the following URL:
index.php?articleID=1
If you use POST, you'll put the data in the request body itself, so you wouldn't be able to tell what value you sent to the server without opening the packet in question and examining the request.
You'll find more information on how to perform these requests back at jQuery's reference site. More information about GET and POST.
You are the architect of the application, so you would know best what method to use. As for contacting the view itself, it's certainly possible albeit questionable from an architectural point of view.

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).

Should my framework allow access to $_GET and $_POST at the same time?

I know you can use both $_GET and $_POST at the same time, but is this a required "feature"? I am writing a framework, where you can access input through:
$value = $this->input->get('name','');
$value = $this->input->post('name','');
$value = $this->input->cookies('name','');
I'm just thinking here, is there a need for having GET and POST at the same time? Couldn't I just do:
$value = $this->input('name','default value if not set');
To obtain GET/POST data according to which HTTP request was made? Cookies will be only accessible through ->cookies(), but should I use ->get() and ->post() instead of doing something like ->input() ?
Thanks for your input!
It's conceivable that in a REST architecture I'd add a product like so:
POST /products?location=Ottawa HTTP/1.0
name=Book
And the product would automatically be associated with the location in the query params.
In a nutshell: there are semantically valid reasons for allowing both, but they can always be transformed into one or the other. That being said, do you want to enforce that usage on your users?
Yes, but you might want to make sure that when using this code you check that the request method is POST if you are going to change anything as a consequence of the request, rather than treating GET and POST as the same thing.
This is because generally GET requests should not have any side effects, all they should do is 'get' stuff.
Edit
This seems less relevant since you have clarified your question, but I will leave it here anyway
Yes!
I think you must allow access to both $_GET and $_POST at the same time. And I don't think you can just merge them together either. (You can have the option to, like PHP and the ill concieved $_REQUEST.) You could get a request like:
POST /validator?type=strict HTTP/1.1
type=html/text
body=<h1>Hello World</h1>
Note that the variable name type is used twice, but in different scopes! (Once in the URI defining the resource that should handle the POST, and then in the posted entity itself.) In PHP this looks like:
$_GET => ('type' => 'strict')
$_POST => ('type' => 'html/text', 'body' => '<H1>Hellow World</h1>')
PHP:s way of just parsing the URI and putting the parameters there into $_GET is somewhat confusing. A URI is used with most (all?) of the HTTP methods, like POST, GET, PUT, DELETE etc. (Not just GET, like PHP would have you believe.) Maybe you could be revolutionary and use some of your own lingo:
$a = $this->uri('name');//param passed in the URI (same as PHP:s $_GET)
$b = $this->entity('body');//var passed in an entity (same as PHP:s $_POST)
$c = $this->method(); //The HTTP method in question ('GET', 'POST' etc.)
And maybe even some utility functions:
if($this->isGET()){
...
}elseif($this->isPOST()){
...
)
I know, wild and crazy :)
Good luck and have fun!
cheers!
you could use just the input method but with flags incase the user wants input from a specific var:
$this->input('abc', '');
$this->input('abc', '', self::I_POST);
$this->input('abc', '', self::I_GET);
$this->input('abc', '', self::I_COOKIE);
It's generally considered better to use $_GET and $_POST rather than $_REQUEST because it costs you nothing much and it closes off some small set of manipulations of the web site. I'd make the specific-source retrievals at least available in your framework.
I would suggest keeping them separate, since they are used for separate purposes. GET is generally used for display purposes, while POST is used for admin purposes, adding/editing items, confirming choices, etc.
There may also be a slight security problem: someone could like to a page using GET parameters and force execution of something like deleting data - e.g. example.com/index.php?deleteid=123 (Actually this can be done with POST from an external HTML form but is much less common. Anyone can post a link on a forum, blog, anywhere.)
I would recommend keeping both POST and GET vars, since you can't predict how they are going to be used.
Most importantly be sure to validate against security exploits such as XSS, Sql injection in $_[POST|GET] before populating your objects.
I would say it highly depends on the situation. If you simply want to accept some parameters that will change how you display an HTML page (a typical GET variable) it's probably ok to accept both.
If you are going to work with forms, changing data and restricted access; you should look into the domain of CSRF and how this security issue might affect you.
In general, if you can be explicit about either, it's wise to do so.

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