PHP for Xojo Programmers - 0003 - Variables from the URL

URL Variables

This time we’ll work to add variables to the URL like “/products.php?item=widget” rather than create one page for every product. We could have 500 products and only need one PHP page and one HTML Template.

When we talked about Includes we had three files “template.htm”, “helloWorld.php”, and “helloEarth.php”. That worked well but now let’s now use variables to replace the need for multiple PHP pages.


Start off by duplicating “helloEarth.php” and name the new file “products.php” so we have two files “template.htm” and “products.php”:


<button type="button" onclick="<?= $buttonJS ?>"><?= $buttonLabel ?></button>


$buttonLabel = 'Hello';
$buttonJS = "alert('Hello Earth!');";
require_once( 'template.htm' );

PHP URL Variables

There are two ways to pass variables to PHP. The first is passing name / value pairs in the URL like “/products.php?item=Widget&price=10.50”. The are called PHP GET parameters. To access the code and price, we can use $_GET['item'] and $_GET['price'].

As you can imagine, this might not be a good idea as someone could just edit the URL and change the price! In a real world system you’d just pass the code and get the price from a database or another source.

Let’s update the PHP.


$buttonLabel = 'Buy a ' . $_GET['item'] . ' now!';
$buttonJS = "alert( 'A " . $_GET['item'] ." costs $" . $_GET['price'] . ".' );";
require_once( 'template.htm' );


Now upload your files and test it! Or you can try loading this URL:

Once you load the page, feel free to change the URL. Change the item and/or the price, remove both, or add another parameter.

Trust but Verify

While the code above will work, You should never just use the values passed because someone could try in inject code. That’s a big topic.

We’re running the code below at link above. It’s just uses the PHP function htmlspecialchars to encode the these characters to for the PHP GET parameters.

& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

Code with Encoded Parameters.

$item = htmlspecialchars( $_GET['item'], ENT_QUOTES, 'UTF-8', false );
$price = htmlspecialchars( $_GET['price'], ENT_QUOTES, 'UTF-8', false );
$buttonLabel = 'Buy a ' . $item . ' now!';
$buttonJS = "alert( 'A " . $item ." costs $" . $price . ".' );";
require_once( 'template.htm' );
1 Like

I’m guessing that using any of the special chars that are part of an url will cause issues too ?
Ie/ if a url uses & # and those that the browser ( server ? php ?) will split the url up into key value pairs wrong ?
something like

1 Like

Good deduction! I’ve never tried that ( on purpose ) but it looks like the ‘dget’ is just dropped. And the next ampersand, varname, equal for price worked normally.

You would need to URL Encode the ampersand you wish to keep.

1 Like