PHP for Xojo Programmers - 0003 - URL Variables
PHP
Reposted from INN: https://ifnotnil.com/t/php-for-xojo-programmers-0003-variables-from-the-url/1733
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.
Prep
Start off by duplicating "helloEarth.php" and name the new file "products.php" so we have two files "template.htm" and "products.php":
template.htm
<html><body>
<button type="button" onclick="<?= $buttonJS ?>"><?= $buttonLabel ?></button>
</body></html>
products.php
<?php
$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.
products.php
<?php
$buttonLabel = 'Buy a ' . $_GET['item'] . ' now!';
$buttonJS = "alert( 'A " . $_GET['item'] ." costs $" . $_GET['price'] . ".' );";
require_once( 'template.htm' );
?>
Test
Now upload your files and test it! Or you can try loading this URL: https://campsoftware.com/labs/inn/0003/products.php?item=Widget&price=10.50
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 &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >
Code with Encoded Parameters.
<?php
$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' );
?>