How to Parse a URL in PHP?

Parsing a URL in PHP is simple with the parse_url function. Here's a step-by-step guide on how to do it:

  1. Using the parse_url Function
$url_components = parse_url("https://example.com/path?name=value#hash");
  1. Accessing URL Components
echo $url_components['scheme'];   // Output: https
echo $url_components['host'];     // Output: example.com
echo $url_components['path'];     // Output: /path
echo $url_components['query'];    // Output: name=value
echo $url_components['fragment']; // Output: hash
  1. Working with URL Parameters
// Get an associative array of URL parameters
parse_str($url_components['query'], $params);
print_r($params);  // Output: Array ( [name] => value )
  1. Modifying and Reconstructing URLs
// Create a new URL with modified components
$new_url_components = $url_components;
$new_url_components['path'] = '/newpath';

$new_url = http_build_url($new_url_components);
echo $new_url;  // Output: https://example.com/newpath?name=value#hash

With the parse_url function and other PHP utilities, parsing a URL in PHP is straightforward, enabling you to access, analyze, and modify URLs with ease.

Lastly, if you want to grab query parameters from any url without using php, use parseurlonline.com to quickly get the data without any hassle.