How to Read and Get URL Parameters in PHP


- Getting & Extracting URL Query Parameters in PHP
- What are URL parameters / query strings?
- PHP’s built‑in mechanism: $_GET
- Extracting from an arbitrary URL string
- Getting the full current URL
- Helper functions
- Edge Cases & Best Practices
- Summary
Getting & Extracting URL Query Parameters in PHP
When building PHP web applications, it's very common to need to read values passed via the URL (the “query string” or GET parameters). In this post, we'll cover:
- What URL parameters (query strings) are
- How PHP makes them available
- How to parse parameters from a URL string
- Useful helper functions
- Edge cases, security, and best practices
What are URL parameters / query strings?
A URL parameter (or query string) is the portion of a URL after the ?
character, with key/value pairs separated by &
. For example:
https://example.com/search.php?q=php&lang=en&page=2
Here:
-
q
=php
-
lang
=en
-
page
=2
These are traditionally accessed via HTTP GET. They allow passing small amounts of data in the URL itself.
$_GET
PHP’s built‑in mechanism: The simplest and most common way to access URL parameters in PHP is via the superglobal $_GET
. This is an associative array that PHP fills from the query string of the current request.
<?php// Suppose URL is: http://mysite.com/page.php?user=alice&age=30 $user = $_GET['user']; // “alice”$age = $_GET['age']; // “30” // Better: check existenceif (isset($_GET['user'])) { $user = $_GET['user'];} else { $user = null;}?>
You can also use the null coalescing operator (PHP 7+):
$user = $_GET['user'] ?? null;
With filtering:
$user = filter_input(INPUT_GET, 'user', FILTER_SANITIZE_STRING);
Notes:
-
$_GET
works whenever a query string is present, regardless of request method. - Always validate and sanitize data.
- Use
isset()
,??
, orfilter_input()
to avoid notices. - Arrays (
?arr[]=foo&arr[]=bar
) are automatically handled.
Extracting from an arbitrary URL string
Sometimes you need to parse parameters from a URL string, not the current request. In that case:
parse_url()
+ parse_str()
<?php$url = "https://example.com/path?foo=bar&baz=qux&arr[]=one&arr[]=two"; $parts = parse_url($url); if (!empty($parts['query'])) { parse_str($parts['query'], $queryParams); // ["foo"=>"bar", "baz"=>"qux", "arr"=>["one", "two"] ]} else { $queryParams = [];}?>
Or shorter:
parse_str(parse_url($url, PHP_URL_QUERY), $queryParams);
Cautions:
- Don’t call
parse_str()
without the second argument, it pollutes the local scope. - Spaces/dots in keys become underscores.
-
max_input_vars
can limit the number of parameters parsed.
Regex alternative
if (preg_match("/[?&]foo=([^&]+)/", $url, $matches)) { $fooVal = urldecode($matches[1]);}
But this is brittle, built‑ins are preferred.
Getting the full current URL
If you need the complete current request URL:
<?phpfunction getCurrentUrl(): string { $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"; $host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; return $scheme . "://" . $host . $uri;} $current = getCurrentUrl();echo $current;?>
This gives something like:
https://example.com/search.php?lang=en&q=php
Helper functions
<?phpfunction getQueryParams(?string $url = null): array { if ($url === null) { $qs = $_SERVER['QUERY_STRING'] ?? ''; parse_str($qs, $params); return $params; } $parts = parse_url($url); if (empty($parts['query'])) { return []; } parse_str($parts['query'], $params); return $params;} function getParam(string $key, ?string $url = null, $default = null) { $params = getQueryParams($url); return $params[$key] ?? $default;}?>
Usage:
$params = getQueryParams("https://example.com/?a=1&b=2");$email = getParam('email', null, '');
Edge Cases & Best Practices
Concern | Tip |
---|---|
Missing keys | Use isset() , ?? , or array_key_exists . |
URL encoding | Automatically handled by PHP. |
Repeated keys | parse_str() keeps the last value unless [] syntax is used. |
Many params | Limited by max_input_vars . |
Security | Always validate and sanitize. |
Malformed URLs | Guard against invalid inputs. |
Summary
- Use
$_GET
for current request parameters. - Use
parse_url()
+parse_str()
for arbitrary URLs. - Encapsulate parsing in helpers.
- Always validate and sanitize input.
Stay Updated.
I'll you email you as soon as new, fresh content is published.
Latest Posts