PHP में URL से query parameters extract करने के built-in functions।
विधि 1: parse_url() + parse_str() (Standard)
<?php
$url = 'https://example.com/register?name=demo&email=amit@example.com&age=25';
// Step 1: URL parse करें
$parts = parse_url($url);
/*
Array
(
[scheme] => https
[host] => example.com
[path] => /register
[query] => name=demo&email=amit@example.com&age=25
)
*/
// Step 2: Query string को array में parse करें
$params = [];
if (isset($parts['query'])) {
parse_str($parts['query'], $params);
}
print_r($params);
/*
Array
(
[name] => demo
[email] => amit@example.com
[age] => 25
)
*/
// Access individual params
echo $params['email']; // amit@example.com
विधि 2: parse_str() Directly (Current Page के लिए)
<?php // Current request के लिए parse_str($_SERVER['QUERY_STRING'], $params); // या $params = $_GET; // Already parsed by PHP // Arbitrary query string के लिए $queryString = 'name=demo&email=amit@example.com&tags[]=php&tags[]=dev'; parse_str($queryString, $params); // $params['tags'] = ['php', 'dev'] - arrays automatically handled!
विधि 3: $_GET Superglobal (Current Request)
<?php // Current page के query parameters $name = $_GET['name'] ?? 'default'; $email = $_GET['email'] ?? null; $tags = $_GET['tags'] ?? []; // Array if tags[]=a&tags[]=b // All params $allParams = $_GET;
विधि 4: HTTP Query String Build करना (Reverse)
<?php
$params = [
'name' => 'अमित',
'email' => 'amit@example.com',
'tags' => ['php', 'developer'],
'active' => true
];
// http_build_query - arrays को proper format में convert करता है
$queryString = http_build_query($params);
// name=%E0%A4%85%E0%A4%AE%E0%A4%BF%E0%A4%A4&email=amit%40example.com&tags[0]=php&tags[1]=developer&active=1
$url = 'https://example.com/api?' . $queryString;
उन्नत: URL Class (PHP 8.0+)
<?php
// PHP 8.0+ - Uri\Url (experimental) या PECL http
// अभी standard library में नहीं, लेकिन polyfills उपलब्ध
// League/Uri (composer require league/uri)
use League\Uri\Parser;
$parser = new Parser();
$uri = $parser->parse('https://example.com/path?name=value#fragment');
echo $uri->getQuery(); // name=value
parse_str($uri->getQuery(), $params);
सामान्य उपयोग के मामले
| Scenario | Code |
|---|---|
| Single param प्राप्त करें | $id = $_GET['id'] ?? null; |
| All params as array | $params = $_GET; |
| External URL parse | parse_str(parse_url($url, PHP_URL_QUERY), $params); |
| URL rebuild with modifications | http_build_query(array_merge($_GET, ['page' => 2])) |
| Remove specific param | unset($params['utm_source']); http_build_query($params); |
Security Notes
- हमेशा
htmlspecialchars()उपयोग करें output में parse_str()बिना second argument के variables create करता है (deprecated behavior) - हमेशा array pass करें- User input को validate/sanitize करें before use