Here is a generated php link:
|
1 |
<a href="secondpage.php?name=Kevin&id=1">Secondpage</a> |
What If for example the value of “name”, instead of “Kevin”, contains sensible characters like “&” or spaces that interfere with an URL?
|
1 |
<a href="secondpage.php?name=Kevin&&id=1">Secondpage</a> |
We are going to use URL encoding
We are going to do some transformations using php to make sure the value is safe before it is sent to the URL
Lets start by setting up some variables:
|
1 2 3 4 5 6 |
<?php
$url_page = 'php/created/page/url.php';
$param1 = 'this is a string';
$param2 = '"bad"/<>characters$';
$linktext = "<Click> & you'll see";
?> |
How can we put together a URL that’s going to be encoded and not break for us?
We are going to use the following functions:
- rawurlencode() – we will use this before the question mark;
- urlencode() – we will use this after the question mark;
- htmlspecialchars() – escapes any html that might due bad things to our html page.
|
1 2 3 4 5 6 7 |
<?php
// this gives us a clean url to use
$url = "http://www.mysite.com/";
$url .= rawurlencode($url_page); // we use rawurlencode because this is before the question mark
$url .= "?param1=".urlencode($param1); // we use urlencode because it's after the question mark
$url .= "¶m2=".urlencode($param2);
?> |
Our URL will be like this:
|
1 |
<a href="<? echo htmlspecialchars($url); ?>"><? echo htmlspecialchars($linktext); ?></a> |
We’ve done two things, cleaned up the link so that we can use it and then we’ve done our htmlspecialchars so that we can safely display that link.