How to Get Parameters from a URL
Friendly & Normal URLs
Getting Parameters from a Normal URL
Normally, parameters are sent after the ?
in a URL.
Example: https://example.com/page.php?article=this-title-is-not-clickbait
To access this variable, you can use the $_GET
global variable.
$articleslug = $_GET['article'];
if ($articleslug != "") {
echo "<p>Article Slug: " . htmlspecialchars($articleslug , ENT_QUOTES);
}
This would assign "this-title-is-not-clickbait" to the variable $articleslug
.
Getting Parameters from a Friendly URL
If you are using friendly URLs that do not have a ?
, you would use a different approach.
Example: https://example.com/article/this-title-is-not-clickbait
First, you would need to get the URL.
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
If you want the last part of the path, you could use this:
echo basename(parse_url($url, PHP_URL_PATH));
It's output would be: "this-title-is-not-clickbait"
But if you want the whole path, not including the domain name, you would use this:
echo trim(parse_url($url, PHP_URL_PATH), '/');
It's output would be "articles/this-title-is-not-clickbait"
Sanatizing Content
Don't forget to sanitize!
For output to the screen, use:
htmlspecialchars($_GET['id'], ENT_QUOTES)
For data going into a query, use:
pg_escape_string($_GET['username'])
Content for tab 2.
Content for tab 3.