Passing variable values in the url with php

Posted On Jan 27, 2008 at 8:56 pm

PHP Tutorial: Passing Variables via URL

In PHP you have the ability to pass information between pages through the URL. This technique is extremely simple and great for things such as telling a script what bit of information is needs to load (example: a forum topic).

The format used to pass variables in the URL is the url itself, followed by a question mark, followed by the list of variables and variable data seperated by the amperand symbol. Example:

www.domain.com/index.php?variable1Name=theFirstValue&variable2Name=theSecondValue

Proper XHTML Coding

I should make a point right now that to be W3C valid in xhtml strict, you cannot have the & symbol anywhere in your code, instead, you must use & in the source code, which gets parsed as an amperand symbol by your browser. So if you wanted to link to the above URL example in html, the link code would look like:

<a href="www.domain.com/index.php?variable1Name=theFirstValue&amp;variable2Name=theSecondValue">Link Title</a>

Accessing the variables in PHP

When a php page is loaded with properly formated variables in the URL, they can be accessed through the $_GET['variableName'] array in php. You simply replace variableName and you can access the data for the specified variable. Using the above URL example, lets see how php can access and output the data:

<? $v1 = $_GET['variable1Name']; $v2 = $_GET['variable2Name']; echo "Variable One Value: $v1
Variable Two Value: $v2
"; ?>

Creating url variables with php

When creating a script that will be passing data through the URL, you have to keep in mind the possibility of characters causing parse errors in the URL. The best way to overcome such problems is to use the urlencode() PHP function. This will take a string of data and return it with all special characters trasformed into URL-friendly entities.

<a href="index.php?variableName=<? echo urlencode(" 'hello & goodbye' "); ?>"></a>

The above value of 'hello & goodbye' will then be transformed into +%27hello+%26+goodbye%27+ making it completely safe to use within a URL.

This topic has the following tags:

Last 5 Linkbacks

Post Comment

You are replying to cancel reply

Your email address will not be visible to the public

Avatars by Gravatar. Join Gravatar for free to have your avatar shown everywhere you post.