How to Get Parameters from a URL String with PHP

Almost all developers at least once in their practice have wondered how to get parameters from a URL string with the help of PHP functions.

In our tutorial, we will provide you with two simple and handy functions such as pase_url() and parse_str() that will allow you to do that.

Read on and check out the options below.

Before starting, note that the parameters and the URL are separated by the ? character.

In case you want to get the current URI you can use $url = $_SERVER[REQUEST_URI];

Watch a course Learn object oriented PHP

Using the parse_url() and the parse_str Functions

This function is aimed at returning the URL components by parsing the URL.

So, it parses the URL, returning an associative array that encompasses different components.

The syntax of the parse_url() function is as follows:

parse_url($url, $component = -1);

With the help of the parse_str() function, you can parse query strings into variables.

The syntax of this function is like so:

parse_str($string, $array);

Now, let’s see examples of how to use these two functions for getting the parameters from the URL string.

<?php

// Initialize URL to the variable
$url = 'http://w3docs.com?name=John';

// Use parse_url() function to parse the URL
// and return an associative array which
// contains its various components
$url_components = parse_url($url);

// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);

// Display result
echo ' Hi ' . $params['name'];

?>

The output of this example will be:

    Hi John

Now, let’s consider another example:

<?php

// Initialize URL to the variable
$url = 'http://w3docs.com/register?name=Andy&[email protected]';

// Use parse_url() function to parse the URL
// and return an associative array which
// contains its various components
$url_components = parse_url($url);

// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);

// Display result
echo ' Hi ' . $params['name'] . ' your emailID is ' . $params['email'];

?>

And, the output of this example will look like this:

  Hi Andy your emailID is [email protected]

So, in this tutorial, we highlighted the two handy functions that will allow getting parameters from a URL string with PHP.

Hope, this tutorial helped to achieve your goals.