How can I get parameters from a URL string?
You can use the parse_url()
and parse_str()
for that.
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
If you want to get the $url
dynamically with PHP, take a look at this question:
Get the full URL in PHP
How can I get query string values in JavaScript?
Update: Jan-2022
Using Proxy()
is more performant than using Object.fromEntries()
and better supported
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
Update: June-2021
For a specific case when you need all query params:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
Update: Sep-2018
You can use URLSearchParams which is simple and has decent (but not complete) browser support.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Original
You don't need jQuery for that purpose. You can use just some pure JavaScript:
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
Usage:
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
NOTE: If a parameter is present several times (?foo=lorem&foo=ipsum
), you will get the first value (lorem
). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp
NOTE: If you're getting a no-useless-escape eslint error, you can replace name = name.replace(/[\[\]]/g, '\\$&');
with name = name.replace(/[[\]]/g, '\\$&')
.
This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.
Get the values from the GET parameters (JavaScript)
JavaScript itself has nothing built in for handling query string parameters.
Code running in a (modern) browser can use the URL
object (a Web API). URL
is also implemented by Node.js:
// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
How do I extract query parameters from a URL string in PHP?
You can use parse_url
and parse_str
like this:
$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];
parse_url
allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc
). Then we can parse the query with parse_str
.
How can I get (query string) parameters from the URL in Next.js?
Get it by using the below code in the about.js page:
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
<p>Welcome to About! { name }</p>
)
Retrieving parameters from a URL
This is not specific to Django, but for Python in general. For a Django specific answer, see this one from @jball037
Python 2:
import urlparse
url = 'https://www.example.com/some_path?some_key=some_value'
parsed = urlparse.urlparse(url)
captured_value = urlparse.parse_qs(parsed.query)['some_key'][0]
print captured_value
Python 3:
from urllib.parse import urlparse
from urllib.parse import parse_qs
url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]
print(captured_value)
parse_qs
returns a list. The [0]
gets the first item of the list so the output of each script is some_value
Here's the 'parse_qs' documentation for Python 3
Get URL query string parameters
$_SERVER['QUERY_STRING']
contains the data that you are looking for.
DOCUMENTATION
- php.net: $_SERVER - Manual
Get the value of URL Parameters
You can use the belowCode to get the param
func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
Call the method like let test1 = getQueryStringParameter(url, param: "test1")
Other method with extension:
extension URL {
public var queryParameters: [String: String]? {
guard
let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
How to get parameter value from query string?
React Router v6, using hooks
In react-router-dom v6 there's a new hook named useSearchParams. So with
const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")
you will get "blablabla"
. Note, that searchParams is an instance of URLSearchParams, which also implements an iterator, e.g. for using Object.fromEntries etc.
React Router v4/v5, without hooks, generic
React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search
(or useLocation, see below). For reasons see nbeuchat's answer.
E.g. with qs library imported as qs
you could do
qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
Another library would be query-string. See this answer for some more ideas on parsing the search string. If you do not need IE-compatibility you can also use
new URLSearchParams(this.props.location.search).get("__firebase_request_key")
For functional components you would replace this.props.location
with the hook useLocation. Note, you could use window.location.search
, but this won't allow to trigger React rendering on changes.
If your (non-functional) component is not a direct child of a Switch
you need to use withRouter to access any of the router provided props.
React Router v3
React Router already parses the location for you and passes it to your RouteComponent as props. You can access the query (after ? in the url) part via
this.props.location.query.__firebase_request_key
If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via
this.props.match.params.redirectParam
This applies to late React Router v3 versions (not sure which). Older router versions were reported to use this.props.params.redirectParam
.
General
nizam.sp's suggestion to do
console.log(this.props)
will be helpful in any case.
Related Topics
PHP + MySQL Transactions Examples
How to Call a JavaScript Function from PHP
Detect Encoding and Make Everything Utf-8
Is There a Code Obfuscator For PHP
How to Get Id of the Last Updated Row in MySQL
Convert Multidimensional Array into Single Array
How to Get an Array of Specific "Key" in Multidimensional Array Without Looping
Formatting a Number With Leading Zeros in PHP
Stacking Multiple Ternary Operators in PHP
Laravel 5 - Remove Public from Url