244

I have an HTML form field $_POST["url"], having some URL strings as the value.

Example values are:

https://example.com/test/1234?email=xyz@test.com
https://example.com/test/1234?basic=2&email=xyz2@test.com
https://example.com/test/1234?email=xyz3@test.com
https://example.com/test/1234?email=xyz4@test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5@test.com

etc.

How can I get only the email parameter from these URLs/values?

Please note that I am not getting these strings from the browser address bar.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Asim Zaidi
  • 25,390
  • 48
  • 128
  • 219
  • I'm a little confused, please elaborate the Q... – Dexter Huinda Jul 14 '12 at 03:30
  • Are you saying/asking for the URLs to be treated as strings? – hjpotter92 Jul 14 '12 at 03:39
  • If you want to "match" the email part from strings, like in your examples, use regular expressions. Could be as simple as `/(email=\w\@\w\.\w)/` or more advanced matching techniques. Just giving you the idea. See `preg_match` function: http://php.net/manual/en/function.preg-match.php – Dexter Huinda Jul 14 '12 at 03:43
  • possible duplicate of [How do I extract query parameters from an URL string in PHP?](http://stackoverflow.com/questions/4784243/how-do-i-extract-query-parameters-from-an-url-string-in-php) – Always_a_learner Jul 08 '15 at 05:11
  • Possible duplicate of [Get URL query string](https://stackoverflow.com/q/8469767/608639) – jww Oct 21 '18 at 06:08

13 Answers13

490

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

Community
  • 1
  • 1
Ruel
  • 14,929
  • 7
  • 36
  • 49
  • 3
    its working but i am getting error in logs like this : PHP Notice: Undefined index: query – Srinivas08 Sep 11 '18 at 13:52
  • Also, you will have a question mark if it is the last character in the query. I used this: `if (strpos($urlParts['path'], '?')) { $urlParts['path'] = substr($urlParts['path'], 0, strpos($urlParts['path'], '?')); }` to remove it from the end. – Utmost Creator Apr 29 '21 at 14:09
137

All the parameters after ? can be accessed using $_GET array. So,

echo $_GET['email'];

will extract the emails from urls.

hjpotter92
  • 75,209
  • 33
  • 136
  • 171
  • 64
    This isn't the answer to the question, but this is the answer I was looking for when I asked the Googles for the question, so +1 for answering Google correctly. – BillyNair Feb 17 '16 at 18:44
  • 1
    This may not be the answer to question but is the correct and easiest way to get URL parameters--if they are set correctly: `https://example.com?email=myemail@example.com` `$email = $_GET['email']; $email === 'myemail@example.com';` – CheddarMonkey Jul 23 '19 at 22:56
50

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 ) 
JCotton
  • 11,400
  • 5
  • 53
  • 57
13

As mentioned in another answer, the best solution is using parse_url().

You need to use a combination of parse_url() and parse_str().

The parse_url() parses the URL and return its components that you can get the query string using the query key. Then you should use parse_str() that parses the query string and returns values into a 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: preg_match()

You can use preg_match() to get a specific value of the query string from a URL.

preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // xyz2@test.com

preg_replace()

Also you can use preg_replace() to do this work in one line!

$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// xyz2@test.com
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mohammad
  • 20,339
  • 15
  • 51
  • 79
  • I'm using Laravel. The `preg_replace()` method works best here because it doesn't throw error when `query` isn't defined in the URL unlike `parse_url()`, and it's a one liner! – Laurensius Adi Feb 16 '21 at 14:01
8

Use $_GET['email'] for parameters in URL. Use $_POST['email'] for posted data to script. Or use _$REQUEST for both. Also, as mentioned, you can use parse_url() function that returns all parts of URL. Use a part called 'query' - there you can find your email parameter. More info: http://php.net/manual/en/function.parse-url.php

Sourabh Kumar Sharma
  • 2,804
  • 3
  • 21
  • 32
Paul Denisevich
  • 2,284
  • 12
  • 17
7

You can use the below code to get the email address after ? in the URL:

<?php
if (isset($_GET['email'])) {
    echo $_GET['email'];
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Gulshan kumar
  • 331
  • 3
  • 7
  • 4
    The OP requested extracting variables from a string not the URL in current page. parse_url() is the correct answer assuming the string is correctly formatted. – Bloafer Feb 08 '16 at 10:44
3

I a created function from Ruel's answer.

You can use this:

function get_valueFromStringUrl($url , $parameter_name)
{
    $parts = parse_url($url);
    if(isset($parts['query']))
    {
        parse_str($parts['query'], $query);
        if(isset($query[$parameter_name]))
        {
            return $query[$parameter_name];
        }
        else
        {
            return null;
        }
    }
    else
    {
        return null;
    }
}

Example:

$url = "https://example.com/test/the-page-here/1234?someurl=key&email=xyz5@test.com";
echo get_valueFromStringUrl($url , "email");

Thanks to @Ruel.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
mghhgm
  • 1,547
  • 22
  • 42
2
$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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Asesha George
  • 2,002
  • 1
  • 26
  • 62
2

A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.

squarecandy
  • 4,458
  • 2
  • 32
  • 42
  • whooops, didn't see the last line of the questions about not getting this from the URL... still leaving this here in case it's helpful to anyone. – squarecandy Feb 18 '20 at 17:49
1
$web_url = 'http://www.writephponline.com?name=shubham&email=singh@gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);

echo "Name: " . $queryArray['name'];  // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh@gmail.com
Nik
  • 2,427
  • 2
  • 22
  • 24
SHUBHAM SINGH
  • 308
  • 2
  • 10
  • An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/57010223/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 19 '21 at 20:07
0

In Laravel, I'm using:

private function getValueFromString(string $string, string $key)
{
    parse_str(parse_url($string, PHP_URL_QUERY), $result);

    return isset($result[$key]) ? $result[$key] : null;
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ronald Araújo
  • 1,197
  • 4
  • 17
  • 29
0

A dynamic function which parses string URL and gets the value of the query parameter passed in the URL:

function getParamFromUrl($url, $paramName){
  parse_str(parse_url($url, PHP_URL_QUERY), $op); // Fetch query parameters from a string and convert to an associative array
  return array_key_exists($paramName, $op) ? $op[$paramName] : "Not Found"; // Check if the key exists in this array
}

Call the function to get a result:

echo getParamFromUrl('https://google.co.in?name=james&surname=bond', 'surname'); // "bond" will be output here
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Bhargav Kaklotara
  • 1,182
  • 10
  • 19
-4

To get parameters from a URL string, I used the 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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ravi Agrawal
  • 69
  • 1
  • 5