Reputation: 12512
I have a page that can have a link to in either one of the formats below:
When the query part of the URL is present, I need to capture it with PHP. I tried using parse_url but I'm not really sure how to use it. Tried this
echo (parse_url($_SERVER['REQUEST_URI']['query']));
but it returns Array...
Upvotes: 0
Views: 10423
Reputation: 22633
parse_url returns an associative array (aka hash, dictionary, etc.) with the following keys:
scheme - e.g. http
host
port
user
pass
path
query - after the question mark ?
fragment - after the hashmark #
which could break down something like this:
scheme user password host port path query fragment
[http]://[santa]:[password]@[www.website.com]:[80]/[page.php]?[var=val]#[anchor]
you appear to be looking for one of these:
$parsedUrl = parse_url($_SERVER['REQUEST_URI']);
echo $parsedUrl['query'];
echo $_SERVER['query_string'];
Upvotes: 1
Reputation: 272106
The optional 2nd parameter of parse_url
allows you to specify precisely what portion of URL you need:
<?php
echo parse_url("http://mydomain.com/linkID", PHP_URL_QUERY); // <empty string>
echo parse_url("http://mydomain.com/linkID?9c1023a67eaf46cae864a31097", PHP_URL_QUERY); // 9c1023a67eaf46cae864a31097
On the other hand, it is easier to use a server variable, if applicable:
echo isset($_SERVER["QUERY_STRING"]) ? $_SERVER["QUERY_STRING"] : "";
Upvotes: 4
Reputation: 43810
$_SERVER['QUERY_STRING'];
This should be all you need. See $_SERVER variables
Upvotes: 1
Reputation: 4874
You should do:
$parsed = parse_url($_SERVER['REQUEST_URI']);
echo $parsed['query'];
EDIT:
If you only need the query part of the URL and nothing more the solution of Salman below is actually a bit nicer:
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
Upvotes: 6