Get Parameters From URL String in PHP

Use parse_url() with parse_str() functions

Use parse_url() with parse_str() to get parameters from URL String in PHP. The parse_url() function is used to return the components of a URL by parsing it and parse_str() is used to create an associate array of query parameters and their values.

Once you have the array of query parameters, you can easily access the individual values using the array keys. For example, to access the value of the id and category parameter, you could use the following code:

We used parse_url() function to return the components of a URL by parsing it in form of associate array.

parse_url() function takes a string containing the URL as an argument and returns an associative array that contains its various components.

The following table lists the components that can be retrieved by this function:

  • scheme: specifies the protocol to be used to access the resource on the Internet.
  • host: specifies the host name or the IP address of the server.
  • port: specifies the port number to be used on the server.
  • user: specifies the username to be used for logging into the server.
  • pass: specifies the password to be used for logging into the server. path Specifies the path to be used on the server.
  • query: specifies the query string to be sent to the server.
  • fragment: specifies the fragment identifier.

Let’s have an example

The following example shows how to use the parse_url() function:

This will produce the following result:

If you want to retrieve a specific component from the URL, you can use the following syntax:

The $component parameter specifies the component to be retrieved.

For example, if you want to retrieve only the query string from the URL, you can use the following code:

This will produce the following result:

Once we have query parameters, we used parse_str() to parse query string into an array of key/values pairs.

parse_str() parses the String into array of variables.

That’s all about how to get parameters from URL String in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *