I have a HTML form field $_POST[\"url\"]
having some URL strings as the value.
Example values are:
https://example.com/test/1234?email=xyz@test.com
To get parameters from URL string, I used following function.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var email = getUrlParameter('email');
If there are many URL strings, then you can use loop to get parameter 'email' from all those URL strings and store them in array.
$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- see the value
This is working great for me using php
As mentioned in other answer, best solution is using
You need to use combination of parse_url()
and parse_str().
The parse_url()
parse URL and return its components that you can get query string using query
key. Then you should use parse_str()
that parse query string and return
values into variable.
$url = "https://example.com/test/1234?basic=2&email=xyz2@test.com";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // xyz2@test.com
Also you can do this work using regex.
You can use preg_match()
to get specific value of query string from URL.
preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // xyz2@test.com
Also you can use preg_replace()
to do this work in one line!
$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// xyz2@test.com
All the parameters after ?
can be accessed using $_GET
array. So,
echo $_GET['email'];
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url()
will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str()
will create variables for each of the parameters in the query string. I don't like polluting the current context, so providing a second parameter puts all the variables into an associative array.
$url = "https://mysite.com/test/1234?email=xyz4@test.com&testin=123";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);
//Output: Array ( [email] => xyz4@test.com [testin] => 123 )
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