3) URL Parameter

Sending value from one page to another.

There are many ways in PHP through we can send values from one page to another
One of these is by URL parameter

like : www.codedecode.co.in?page=2

URL parameter comes after the question mark with a format name of parameter than equal sign and then the value of the parameter.

Like page=2

Sending multiple Parameter

www.codedecode.co.in?category=7&page=2

  • Here we are passing data from one page to another via links.
  • We can access the URL parameter with the help of super global variable $_GET
  • Super global variable They are available in all variable scope.

You can read here about super global variable: HERE

To access GET variable

Note: The data type of the value retrieved from $_GET is always a string even if we pass number 2

Ex: Change the datatype to int

Default values for URL:

If we retrieve the value that does not exist PHP page will give error so make sure the value is present before you retrieve it.

This although solved our problem but that is too much code to write over and over again for all URLs. It is better to use a ternary operator

You can read all about ternary operator here

Encode URL Parameter:

If we want to give some other values to the URL parameter in place id then we have to encode URL parameter
Lets us take an example of why we need the encoding:

Example

codedecode.co.in?name=mastor&son

Here URL parameter is “master&son” but & has special meaning in URL parameter as discussed above. So we need to use encoding. we use the function urlencode

  • Letters, number, underscore and dash are unchanged with this.
  • Reserved characters are encoded.
  • Urlencode spaces become “+”.

Use of htmlspecialchars

Usage:

When we build dynamic data then we may have some section where the data come from users. It might be a possibility that some nasty user may try to inject some random HTML code that can break our site.

So we use htmlspecialchars

Note: anywhere dynamic data you must provide htmlspecial chars