tags:

views:

123

answers:

4

Hi, i think this is a bit of a noob question, but here goes.

I am trying to get a better understanding $_GET variables in PHP. A lot of CMS's etc convert things like site.com/?ID=42 into something like site.com/42

My question is, what happens to the $_GET variables when this happens? I try and print the GET array on page load, and it is empty.

A: 

If you pass arguments this way, they will no longer be GET variables as they are not passed using the traditional ? GET syntax. They are just part of the URL, which will be parsed by the "CMS" framework you are using.

However, if you happened to pass a "traditional" GET variable and want to read it on the server, you would have to consult the CMS's documentation. If the framework is going to use pretty URL's it will probably also remove any GET variables, as they are no longer necessary. For example, the CodeIgniter MVC framework (not a CMS on its own, but may used to build them) does this.

Justin Ethier
A: 

You can do something like site.com/42 and retain a GET variable of ID=42 by adding a proper rewrite rule. For example, assuming you're running Apache Web Server, you could modify your .htaccess file (located in your webroot directory) with the following:

RewriteEngine On
RewriteRule ^(.*) /?id=$1 [L]
jwhat
+2  A: 

The way they do this is using mod_rewrite

Basically you have the webserver "rewrite" URI requests to something else, so you have incoming requests like

http://your.site.com/Page/arg1/arg2/arg3

But with your REWRITE RULE, you'll have Apache turn requests that match this pattern (all requests bound for /Page) into:

http://your.site.com/Page?a=arg1&b=arg2&c=arg3

You'd then finally in PHP have $_GET[ 'a' ], $_GET[ 'b' ] and $_GET[ 'c' ] all set to values.

Check out this book

bobobobo
A: 

The thing, it's not a GET variable anymore, the variable just becomes part of the URL. These URLs are then custom parsed by the application. Most MVC frameworks follow the rule of /controller/action/params and break the URL down based on the position of the part:

  • First /controller part determines which controller to use
  • Second /action part determines which method to call
  • Any following parameter is just passed as argument to the receiving function, the meaning depends on the function and the order
  • Some also use named parameters like /page:2, so they don't have to depend on the right order

This can all be customized. You can also use your web server (e.g. Apache) to rewrite these types of URLs into good old GET param URLs before they even hit your application.

deceze