Get URL query string parameters - php

What is the "less code needed" way to get parameters from a URL query string which is formatted like the following?
www.mysite.com/category/subcategory?myqueryhash
Output should be: myqueryhash
I am aware of this approach:
www.mysite.com/category/subcategory?q=myquery
<?php
echo $_GET['q']; //Output: myquery
?>

$_SERVER['QUERY_STRING'] contains the data that you are looking for.
DOCUMENTATION
php.net: $_SERVER - Manual

The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
Example:
$url = 'www.mysite.com/category/subcategory?myqueryhash';
echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"
Full documentation here

The function parse_str() automatically reads all query parameters into an array.
For example, if the URL is http://www.example.com/page.php?x=100&y=200, the code
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
will store parameter values into the $queries array ($queries['x']=100, $queries['y']=200).
Look at documentation of parse_str
EDIT
According to the PHP documentation, parse_str() should only be used with a second parameter (array). Using parse_str($_SERVER['QUERY_STRING']) on this URL will create variables $x and $y, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1.

If you want the whole query string:
$_SERVER["QUERY_STRING"]

I will recommend the best answer as:
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
The above example will output:
Hello Hannes!

Programming Language: PHP
// Inintialize a URL to the variable
$url = 'https://www.youtube.com/watch?v=qnMxsGeDz90';
// Use parse_url() function to parse the URL
// and return an associative array which contains its various components
$url_components = parse_url($url);
// Use the parse_str() function to parse the
// string passed via the URL
parse_str($url_components['query'], $params);
// Display result
echo 'v parameter value is ' . $params['v'];
This worked for me.

Also if you are looking for current file name along with the query string, you will just need following
basename($_SERVER['REQUEST_URI'])
It would provide you info like following example
file.php?arg1=val&arg2=val
And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing
$_SERVER['REQUEST_URI']

This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;)
is taken from:
http://php.net/manual/en/function.parse-str.php#76792
Credits go to Evan K.
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');
# the above produces:
$foo = array('foo' => '3');
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');
# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>
This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:
<?php
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>

Here is my function to rebuild parts of the REFERRER's query string.
If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET vars (e.g. a page number).
Example: Referrer's query string was ?foo=1&bar=2&baz=3 calling refererQueryString( 'foo' , 'baz' ) returns foo=1&baz=3":
function refererQueryString(/* var args */) {
//Return empty string if no referer or no $_GET vars in referer available:
if (!isset($_SERVER['HTTP_REFERER']) ||
empty( $_SERVER['HTTP_REFERER']) ||
empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
return '';
}
//Get URL query of referer (something like "threadID=7&page=8")
$refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
//Which values do you want to extract? (You passed their names as variables.)
$args = func_get_args();
//Get '[key=name]' strings out of referer's URL:
$pairs = explode('&',$refererQueryString);
//String you will return later:
$return = '';
//Analyze retrieved strings and look for the ones of interest:
foreach ($pairs as $pair) {
$keyVal = explode('=',$pair);
$key = &$keyVal[0];
$val = urlencode($keyVal[1]);
//If you passed the name as arg, attach current pair to return string:
if(in_array($key,$args)) {
$return .= '&'. $key . '=' .$val;
}
}
//Here are your returned 'key=value' pairs glued together with "&":
return ltrim($return,'&');
}
//If your referer was 'page.php?foo=1&bar=2&baz=3'
//and you want to header() back to 'page.php?foo=1&baz=3'
//(no 'bar', only foo and baz), then apply:
header('Location: page.php?'.refererQueryString('foo','baz'));

Thanks to #K. Shahzad.
This helps when you want the rewritten query string without any rewrite additions. Let’s say you rewrite the /test/?x=y to index.php?q=test&x=y and you only want the query string.
function get_query_string(){
$arr = explode("?", $_SERVER['REQUEST_URI']);
if (count($arr) == 2){
return "";
}
else{
return "?" . end($arr) . "<br>";
}
}
$query_string = get_query_string();

For getting each node in the URI, you can use function explode() for $_SERVER['REQUEST_URI']. If you want to get strings without knowing if they are passed or not, you may use the function I defined myself to get query parameters from $_REQUEST (as it works both for POST and GET parameters).
function getv($key, $default = '', $data_type = '')
{
$param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);
if (!is_array($param) && $data_type == 'int') {
$param = intval($param);
}
return $param;
}
There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.

Related

How to use only part of a POST value based on conditional

I currently have a PDO script that contains a POST variable that can be either:
RU11223344992 PS:1201012 OR RU11223344992
If the value is like RU11223344992 PS:1201012 the script should interpret it by taking all values to the left of PS:1201012 leaving only RU11223344992
If the value is like RU11223344992 it should interpret it just the way it is.
Depending on this conditional, the value will be assigned to the variable PostValue.
UPDATE:
Using the suggested solution I getting the response Array when doing echo $data
$input = $_POST['postvalue'];
if (strpos($input, "PS: "))
{
$data = explode($input, "PS: ");
}
else{
$data = $input;
}
echo $data;
Can't you use strpos to verify if there's a PS: on your input? Then you can explode it to get the first part (before space) of the string.
$input = $_POST["form-input-name"]
if (strpos($input, " PS:")){
$data = explode(" PS:", $input)[0];
}
else{
$data = $input;
}

Set variable value to function result in PHP

This code:
function getId() {
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
echo $uri_segments[3];
}
...extracts the url segment from a url. Say my url is "mysite.com/a/b/1234"
The code outputs 1234
I want to populate the below code wih 1234 using the function like this
$res = $api->query('bibs/getId();', array(
so its the same as
$res = $api->query('bibs/1234', array(
....but it doesn't work. Any ideas? Do I need to parse or something?
Thanks
The echo statement is described in the manual as:
echo — Output one or more strings
By "output", what is meant here is sending the string to the user - displaying it on the terminal of a command-line script, or sending it to the user's web browser.
What you are looking for is to use the value elsewhere in your code, which is known as "returning" the variable. There is a manual page about returning values.
The next thing you need to do is combine that value with the fixed string 'bibs/'. For that you can use either string concatenation or string interpolation.
In your function you need to actually return the value you want to use of it:
function getId() {
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
return $uri_segments[3];
}
Then you could output the result,
echo getId();
or assign it to another variable
$id = getId();
or use it directly (by concatanating to the other string:
$res = $api->query('bibs/'.getId(), array(...
// the same when assigning it to a variable before:
$id = getId();
$res = $api->query('bibs/'.$id, array(...
Please see IMSoP's answer for very useful explanations and links!
You can try it like this:
$res = $api->query('bibs/' . getId(), array(

PHP: How to get keyless URL parameters

I would like to get the parameter in a key such as http://link.com/?parameter
I read somewhere that the key is NULL and the value would be parameter.
I tried $_GET[NULL] but it didn't seem to work.
Here is my code:
if ($_GET[NULL] == "parameter") {
echo 'Invoked parameter.';
} else {
echo '..';
}
It just prints out .. so that means I'm not doing it right. Can someone please show me the right way.
There are no such things as keyless URL parameters in PHP. ?parameter is the equivalent of $_GET['parameter'] being set to an empty string.
Try doing var_dump($_GET) with a url like http://link.com/?parameter and see what you get.
It should look something like this:
array (size=1)
'parameter' => string '' (length=0)
Thus, you can test it in a couple of ways depending on your application needs:
if (isset($_GET['parameter'])) {
// do something
} else {
// do something else
}
or
// Only recommended if you're 100% sure that 'parameter' will always be in the URL.
// Otherwise this will throw an undefined index error. isset() is a more reliable test.
if ($_GET['parameter'] === '') {
// do something
} else {
// do something else
}
$_GET is a super global assoc array, that contains parameter=>it's value pairs. So, parameter is a key of the array.
For example, if your url is something like this: myweb.com/?page=load&do=magic than you $_GET is:
$_GET(
[page] => load
[do] => magic
)
If you want just to test, if parameter is in you URL as a param, you should do something like this:
if (isset($_GET['parameter'])
echo "Here I am!";
You can also get the entire request_url like this
echo $_SERVER['REQUEST_URI'];
To get the part after ?:
echo explode('?', $_SERVER['REQUEST_URI'])[1];
You can get the part of the URL beginning with ? with
$_SERVER['QUERY_STRING']
You could via array_keys():
$param = array_keys($_GET)[0];
Which would give you the name of the first querystring parameter, whether it has a value or not.
You could also get all of the parameters without a value like so:
$empty = [];
foreach($_GET as $key => $value)
if(strlen($value) === 0) $empty[] = $key;
print_r($empty);

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

Need Help With PHP Function, It doesn't work when i pass value by variable

Here's a php function and it works perfectly.
$values = array(
'php' => 'php hypertext processor',
'other' => array(
'html' => 'hyper text markup language',
'css' => 'cascading style sheet',
'asp' => 'active server pages',
)
);
function show($id='php', $id2='') {
global $values;
if(!empty($id2)) {
$title = $values[$id][$id2];
}
else {
$title = $values[$id];
}
echo $title;
}
When i execute this <?php show(other,asp); ?> it displays active server pages and it works, but when i do it this way it shows an error
<?php
$lang = 'other,asp'
show ($lang);
?>
It doesn't work., Please help me out here
P.S : It works if i pass variable with single value (no commas)
If you'd like to pass it in the way you have it,
maybe try using explode:
function show($id='php') {
global $values;
$ids = explode(',',$id);
if(!empty($ids[1])) {
$title = $values[$ids[0]][$ids[1]];
}
else {
$title = $values[$ids[0]];
}
echo $title;
}
You can't pass two variables in one string. Your string $lang needs to be split up into two vairables:
$lang1 = 'other';
$lang2 = 'asp';
show($lang1, $lang2);
It fails because the key "other,asp" doesn't exist in $values.
In other words, it is trying to evaluate the following:
$title = $values['other,asp'];
PS, it's always useful to provide an actual error rather than saying "it doesn't work".
This is because $lang will get interpreted as a single argument, so $id2 will be 'other,asp'. You need to pass them into the function separately:
$id1 = 'other';
$id2 = 'asp';
show($id1,$id2);
P.S : It works if i pass variable with single value (no commas)
You are assigning $lang to the value 'other,asp', and then passing that sole $lang variable to the show function. There is no key named "other,asp" in your $values array.
Having a comma in the string doesn't mean you're splitting the parameters, it means you're passing a single string value. You have to "pass a variable with a single value", or do it like this for multiple parameter values:
$lang = "other";
$sub_lang = "asp";
show ($lang, $sub_lang);
You are returning one string instead of the two required... how about rewriting your function to handle them instead?

Categories