Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get parameters from a URL string in PHP?
In PHP, you can extract parameters from a URL string using the parse_url() function combined with parse_str(). The parse_url() function breaks down a URL into its components, while parse_str() parses the query string into an associative array.
Syntax
parse_url($url, $component) parse_str($query_string, $result_array)
Basic Example
Here's how to extract specific parameters from a URL ?
<?php
$url = 'http://www.example.com/register?name=demo&email=example12@domain.com';
$res = parse_url($url);
parse_str($res['query'], $params);
echo 'Email = '.$params['email'];
?>
Email = example12@domain.com
Extracting Multiple Parameters
You can access all parameters from the same URL ?
<?php
$url = 'http://www.example.com/register?name=demo&email=example12@domain.com';
$res = parse_url($url);
parse_str($res['query'], $params);
echo 'Name = '.$params['name']."
";
echo 'Email = '.$params['email'];
?>
Name = demo Email = example12@domain.com
Error Handling
Always check if the query component exists to avoid errors ?
<?php
$url = 'http://www.example.com/page';
$res = parse_url($url);
if (isset($res['query'])) {
parse_str($res['query'], $params);
print_r($params);
} else {
echo 'No parameters found in URL';
}
?>
No parameters found in URL
Conclusion
Use parse_url() and parse_str() together to extract URL parameters in PHP. Always check if the query component exists before parsing to prevent errors when dealing with URLs without parameters.
Advertisements
