280

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

Example values are:

https://example.com/test/[email protected]
https://example.com/test/[email protected]
https://example.com/test/[email protected]
https://example.com/test/[email protected]&testin=123
https://example.com/test/the-page-here/[email protected]

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.

5
  • I'm a little confused, please elaborate the Q... Commented Jul 14, 2012 at 3:30
  • Are you saying/asking for the URLs to be treated as strings? Commented Jul 14, 2012 at 3: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: php.net/manual/en/function.preg-match.php Commented Jul 14, 2012 at 3:43
  • possible duplicate of How do I extract query parameters from an URL string in PHP? Commented Jul 8, 2015 at 5:11
  • Possible duplicate of Get URL query string Commented Oct 21, 2018 at 6:08

13 Answers 13

549

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

Sign up to request clarification or add additional context in comments.

2 Comments

its working but i am getting error in logs like this : PHP Notice: Undefined index: query
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.
164

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

echo $_GET['email'];

will extract the emails from urls.

5 Comments

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.
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://[email protected] $email = $_GET['email']; $email === '[email protected]';
can somebody explain why this is not the best answer. it works exactly query params works.
@SaurabhSingh the question is asking how to extract parameters from a URL string that is passed to the server as part of a request. this awnser only get parameters of the page rtequest, it is not how to get parameters from a URL string.
@SaurabhSingh It is because the question is, if the url parameters are unknown, how would you get them. If the URL parameters are known, then this is be correct answer.
60

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/[email protected]&testin=123";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);

//Output: Array ( [email] => [email protected] [testin] => 123 ) 

Comments

19

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 protected]";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // [email protected]

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]; // [email protected]

preg_replace()

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

$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// [email protected]

1 Comment

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!
7

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

1 Comment

OP said he is not getting URLs from address bar. These URLs are just strings IN the code.
6

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

<?php
if (isset($_GET['email'])) {
    echo $_GET['email'];
}

1 Comment

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.
4

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 protected]";
echo get_valueFromStringUrl($url , "email");

Thanks to @Ruel.

Comments

0
$web_url = 'http://www.writephponline.com?name=shubham&[email protected]';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);

echo "Name: " . $queryArray['name'];  // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:[email protected]

1 Comment

An explanation would be in order. E.g., what is the idea/gist? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
0

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.

1 Comment

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.
0

PHP 8.5 (URI with parse_str)

Starting from PHP 8.5, a new URI Extension will be introduced, the existing parse_url() function is still available but may be deprecated in the future.

use Uri\Rfc3986\Uri;

// https://example.com/en.php?abc=abc
// NOTE: I replaced the letter "a" with the ASCII code "%61"
//       to better illustrate the difference
//       between getRawQuery and getQuery
$uri = new Uri('https://example.com/en.php?%61bc=%61bc');

$query = $uri->getQuery();
var_dump($query);
// string(7) "abc=abc"

if ($query !== null) {
  parse_str($query, $params);
  var_dump($params);
  // array(1) {
  //   ["abc"] => string(3) "abc"
  // }
}

getRawQuery returns the raw query (%61bc=%61bc), while getQuery converts ASCII codes into characters (abc=abc).

PHP 8.4 and older (parse_url with parse_str)

Comments

-1

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;
}

Comments

-1

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

Comments

-1

Weird that in over 11 years, nobody has posted an actually good function to do this here. So let me do it. I am not sure if the ! is_string check is actually needed, but it does not hurt.

/**
 * Retrieves the value of a specified query parameter from the given URL.
 *
 * @param string $url The URL from which to retrieve the query parameter.
 * @param string $arg_name The name of the query parameter to retrieve.
 * @return ?string The value of the specified query parameter, or null if it doesn't exist.
 */
function get_url_arg( string $url, string $arg_name ): ?string {

    $query_string = parse_url( $url, PHP_URL_QUERY );

    if ( empty( $query_string ) || ! is_string( $query_string ) ) {
        return null;
    }

    parse_str( $query_string, $query_args );

    return $query_args[ $arg_name ] ?? null;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.