Passing Variables with Data via URL

URL can be used to pass data between pages. This can be achieved by appending variable/value pairs at the end of the URL, starting with ?.

Query String

Let us say we want to pass a variable called name containing the value Jim to a certain page, say, passed-data-via-url.php inside the /sample directory. To pass this, we append the string ?name=Jim after the link to the destination page. We illustrate this by using an anchor tag below

					
					<a href='../sample/passed-data-via-url.php?name=Jim'>To Bridge</a> 
					
				

The text after the URL ?name=Jim is known as the query string.

Retrieving Passed Data

The data passed through the URL can be retrieved in the destination page using the $_GET superglobal and by using the variable name as key

					
					<?php 
						echo $_GET['name']; // Jim 
					?>
					
				

Below is an example link joined with the query string ?name=Jim. If you click on it, the query string ?name=Jim will be found at the end of the URL.

../sample/passed-data-via-url.php?name=Jim

The name "Jim" printed on the page is retrived from the URL using $_GET['name']

Passing Two or More Variables with Data

Two or more variable/value pairs can be passed by separating them with the ampersand (&) character. Say, we want to pass one more additional variable/value pair rank=Captain through the URL in the example above. We append &rank=Captain to the existing query string and pass as shown below

					
					<a href='../sample/passed-data-via-url.php?name=Jim&rank=Captain'>To Bridge</a> 
					
				

Passing Data Outside the Site

Data can be passed through the URL to pages in external websites too. This is usually evident in blogs/sites which do affiliate marketing for various e-commerce and web hosting sites. For example, if you click on a product listed in an Amazon affiliate website, it will lead you to that product's page in Amazon's website with the URL containing some parameters (and corresponding values) like SubscriptionId, tag, linkCode, creativeASIN

Example of Amazon Affiliate Link

Notes

  • URL should not be used for passing sensitive data.
  • If you require the entire query string, you can use $_SERVER[‘QUERY_STRING’]
    							
    							<?php 
    								echo $_SERVER[‘QUERY_STRING’]; // name=Jim 
    							?>