String function to extract only ID from URL - php

I have this string:
solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1
How can I extract just the part of the id, just the value of the ID, the
80d28c22-68d9-11e3-af95-742f689f29f1
I tried the substring function of PHP, the problem is I'm still figuring out how to tell it that it's all the way till the end of the string.
This is what I have so far:
$_solutionID = substr($_currentURL, 17, ??);

try this:
$id = $_GET['id'];
That should work :)

You can retrieve that value from the GET superglobal array: $_GET['id']

You can use $_GET variable for your purpose:
echo $_GET['id'];
# => 80d28c22-68d9-11e3-af95-742f689f29f1
$_GET is a superglobal that is available anywhere in a PHP script, and can be used to check the values of query parameters in a URL, i.e. it stores an associative array of all query parameters of the current page URL.
Also, for reference, if you happen to issue a POST request and would like to find the data that was posted to that URL, you can use $_POST variable in exactly the same manner as the $_GET variable.

I suggest you to use parse_url to extract the query (after the '?') and a regex to extract the id after the 'id='.
$parts = parse_url('solutions.php?id=80d28c22-68d9-11e3-af95-742f689f29f1');
$query = $parts['query'];
$matches = array();
if (preg_match('/id=([-0-9a-z]+)/', $query, $matches) {
return $matches[1];
}

Related

GET Request not working in WordPress

I'm trying to pull a string from my URL in WordPress, and create a function around it in the functions file.
The URL is:
"https://made-up-domain.com/?page_id=2/?variables=78685,66752"
My PHP is:
$string = $_GET("variables");
echo $string;
So I'm trying to return "78685,66752". Nothing happens. Is the first question mark a problem? Or what am I doing incorrectly? Thanks!
$_GET should be in the form
$string = $_GET["variables"];
and not
$string = $_GET("variables");
$_GET is not a function but an Array so correct way of reading it is
$string = $_GET['variables'];
You are also creating the query string all wrong, you should be using
?variables=123,456&page=1
Read more about $_GET here http://php.net/manual/en/reserved.variables.get.php
Your URL should be like:
https://made-up-domain.com/?page_id=2&variables=78685,66752
instead of:
https://made-up-domain.com/?page_id=2/?variables=78685,66752
& char is separating the queries in URL.
And you have syntax error. Use $string = $_GET["variables"]; because $_GET is a superglobal array, not a function.
Use $variables = explode(",", $string); separate values into an array if you want. Simplier way is $variables = explode(",", $_GET["variables"]);
You should format your href and get parameter like this
http://example.com/mypage.html?var1=value1&var2=value2&var3=value3
+ Edit your get method syntax
$string = $_GET['variables'];

How to retrieve an integer part of a URL?

I would like to retrieve part of a url like the last part that will always be an integer. But I don't know how to do it as the last part will change e.g file/Post.php?id=1 and then it could also be file/Post.php?id=26569413146456
How can I do this?
If you want to get it from request, use;
$id = $_GET["id"];
If you want to get it from string, use;
$temp = explode("id=", $your_url);
$id = $temp[1];
The $_REQUEST variable contains both GET and POST arguments.
$_REQUEST['id']
http://www.php.net/manual/en/reserved.variables.request.php
If you will only use http get to fetch the page $_GET['id'] may be used instead but REQUEST contains arguments for GET POST and cookies.
If the URL is the one that requested the current page, you can simply use
$id = $_GET['id'];
Otherwise, for some arbitrary string that you know to contain a URL, you can use parse_url to grab the query string from the URL and parse_str to break down the query components:
$id = "";
$query_string = parse_url($url_string, PHP_URL_QUERY);
if ($query_string) {
parse_str($query_string, $query);
if (isset($query['id'])) {
$id = $query['id'];
}
}

How can I get parameters from a URL string?

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.
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
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 )
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
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
You can use the below code to get the email address after ? in the URL:
<?php
if (isset($_GET['email'])) {
echo $_GET['email'];
}
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.
$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
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.
$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.
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;
}
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

parse_str doesn't work when the question mark is present?

why I get error when I pass the string with something like 'form.php?', for instance,
parse_str('form.php?category=contacts');
echo $category;
I get this,
Notice: Undefined variable: category in C:\wamp\www\1hundred_2011_MVC\applications\CMS\category_manage.php on line xx
but,
parse_str('category=contacts');
echo $category;
I get what I want,
contacts
how can I fix it? I have to pass something like 'xxx.php?category=contacts' to get 'contacts' or something in the variable.
thanks.
The function parse_str only parses the query string, not the entire URL. Try using parse_url with the component set to PHP_URL_QUERY to extract the query string first, then use parse_str on that.
$url_query = parse_url('form.php?category=contacts', PHP_URL_QUERY);
parse_str($url_query, $output);
echo $output['category'];
Result:
contacts
See it at ideone.
parse_str will only accept query strings:
$q = 'foo?hello=world';
parse_str($q);
echo ${'foo?hello'}; // outputs 'world'
Strip the beginning of the URL first:
$q = 'foo?hello=world';
parse_str(substr($q, strpos($q, '?')+1);
echo $hello; // outputs 'world'
Consider using parse_str second argument to have the data in an array instead, to avoid overwriting local variables.
You may want to use urldecode plus return extracted variables like so:
... some helper class...
/**
* Return parsed serialized JQuery object as PHP array of extracted variables
*/
protected static function parseFields($encoded){
parse_str(urldecode($encoded));
unset($encoded);
return get_defined_vars();
}
Also, you may want to utilize the JQuery function "$.param(data)" for creating URL encoded string:
var encoded=$.param(fields);
and submit via AJAX/POST request to server to function parseFields().

How to extract two variables from this string in PHP

I have a string like this :
oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc
How can I extract the two variables oauth_token and oauth_token_secret from the about string using PHP
NOTE: this is not coming from the URL( we can do that using $_GET)
Thank YOU
Use parse_str() for parsing query string parameters.
// Extract into current scope, access as if they were PHP variables
parse_str($str);
echo $oauth_token;
echo $oauth_token_secret;
// Extract into array
parse_str($str, $params);
echo $params['oauth_token'];
echo $params['oauth_token_secret'];
You may wish to urldecode() the variables after you've extracted them.
try this
$text = "oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc"
;
$i=explode('&',$text);
$j=explode('=',$i[0]);
$k=explode('=',$i[1]);
echo $j[0]."<br>";
echo $j[1]."<br>";
echo $k[0]."<br>";
echo $k[1]."<br>";
1, split the two parts of the $string,
$str_array = explode('&',$string);
2, get the part after the "=" sign, so for the oauth_token part:
$oauth_token_array = explode('=',$str_array[0]);
$oauth_token = $oauth_token_array[1];
EDIT: ignore this, it's definitely verbose. BoltClock's the solution.
The best way (most reusable) is to use a function which returns an array similar to $_GET.
edit There is already a function for this: http://www.php.net/manual/en/function.parse-str.php This will work with array get values too.
$values = array();
parse_str($query_strng, $values);
Quite an ugly function, why can't it just return the array of values. It either stuffs them into individual variables or you need to pass in a reference. Come on php, you can do better. /rant

Categories