How to read GET values from HTTP_REFERER with PHP - php

How can I read the values of get header variables which are from $_SERVER["HTTP_REFERER"] such as if I had index.php?col=example&order=example2 how could I read the values of col and order from the string which is received from $_SERVER["HTTP_REFERER"] and would this be safe?
I thought of using strpos() but that would mean I would have to make a function to find the position of col for example and then read the value starting from thr = and stop at the next & or null value if only one get header is set...

Based on a dupe, use parse_str, like this:
$str = 'index.php?col=example&order=example2';
$qs = parse_url($str, PHP_URL_QUERY);
if(!empty($qs)){
parse_str($qs, $output);
// TODO check for key existence
echo $output['col']; // example
echo $output['order']; // example2
}
The difference is that it won't work with index.php?, so we get just the query string part from the url.
I suggest you do some checking to make the script more reliable.

Related

Ampersand doesn't load in Query String - PHP

I'm passing simple query string:
index.php?a=orange&apple
Getting value with:
$_GET['a'];
it only shows orange value. i have tried
$a = urlencode($_GET['a']);
$rs = urldecode($a);
echo $rs; // orange;
but didn't work. Found similar question here stackoverflow but seems not useful. How do i get complete value orange&apple?
That is because & makes apple as another value in GET request.
Like this -
/test/demo_form.php?name1=value1&name2=value2
So use '%26'(encoding URI Component) in place of & like this -
index.php?a=orange%26apple
And get the value with $_GET['a'];. This should work.
Your query string need to encode ampersand(&) as percent-encode as %26. Your url will be like :
index.php?a=orange%26apple
Write it like this:
index.php?a=orange&b=apple
// Values
$_GET['a'];
$_GET['b'];

How to switch between URL variable names and values

For example I have a URL like this one:
index.php?country=Canada
If it is just index.php that means that the default country is USA. People can switch between countries by checking or unchecking a checkbox.
But people can sort their results via GET variables:
State
Surname
Name
But if I use $_SERVER["REQUEST_URI"] then it will always just keep adding new values to my URL array (query string). It works if it is just index.php then I can make it like this:
State
Surname
Name
I know that after index.php it will always be a question mark ? first.
But what when visitors want to keep index.php?country=Canada and just switch between sort=state, sort=surname and sort=name. Then I need to know if a question mark is already in the URL, when to add & mark. I'm not sure how to solve this problem.
Change the way you echo your link:
PHP
<?php
$link = $_SERVER["PHP_SELF"];
if(isset($_GET['country']
$link.="&";
else
$link.="?";
?>
And echo link like this:
HTML
State
NOTE: I deleted the question mark before "sort".
You need logic to dynamically build a querystring, rather than statically adding ? and &.
Something like http_build_query would be the route I'd go, but the information you've provided is small compared with the possibilities you appear to want, so its hard to provide specific code.
Here is some more information about the http_build_query function in PHP. Its purpose is to build a querystring, here is an example of what you might do:
// capture the values into variables, however you want ($_GET is example)
$country = $_GET['country'];
$state = $_GET['state'];
$city = $_GET['city'];
$data = array();
// use logic to dynamically build the array, so long as the variables have values
!empty($country) ? array_push($data,'country'=>$country) : '';
!empty($state) ? array_push($data,'state'=>$state) : '';
!empty($city) ? array_push($data,'city'=>$city) : '';
// apply the array dynamically built
$querystring = http_build_query($data);
// concatenate to form the new URL
$url = 'http://www.example.com/?'.$querystring
If you declared country to be USA and city to be Seattle, but did not declare state, it would produce:
http://www.example.com/?country=USA&city=Seattle
Something along these lines should build the dynamic array you want with only the values you are looking for.
All of the variables in the query string are stored in the $_GET php superglobal array. In your example you can access the country with $_GET['country']. Do default to the USA you can use isset() to check if the variable exists.
$country = "USA";
if(isset($_GET['country'])) {
$country = $_GET['country'];
}
The solution here is to use either $_GET (already mentioned in another answer), or http://php.net/manual/en/function.parse-url.php, which makes the ordering of arguments completely irrelevant. Simply parse the url into an array of query arguments, and test for the ones you need. To turn it all back into a url, you would use http://php.net/manual/en/function.http-build-query.php

Capture value from URL string with php

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44
How can I always find & capture the value of the id which in this example is 2773?
I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.
Thanks
You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).
For example:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
print_r($vars); // see what's in there
// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));
// This will also work:
$id = intval($vars['id']);
echo "The id is $id\n";
See it in action.
You can use parse_str
You can use parse_url to parse URLs!
But you can use, to extract directly the numbers of ID variable:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;

How to change variables in link of foo?q=some&s=3&d=new

Consider a php script visited with URL of foo?q=some&s=3&d=new. I wonder if there is a paractical method for parsing the url to create links with new variable (within php page). For example foo?q=**another-word**&s=3&d=new or foo?q=another-word&s=**11**&d=new
I am thinking of catching the requested URL by $_SERVER['REQUEST_URI'] then parsing with regex; but this is not a good idea in practice. There should be a handy way to parse variables attached to the php script. In fact, inverse action of GET method.
The $_GET variable contains an already parsed array of the current query string. The array union operator + makes it easy to merge new values into that. http_build_query puts them back together into a query string:
echo 'foo?' . http_build_query(array('q' => 'another-word') + $_GET);
If you need more parsing of the URL to get 'foo', use parse_url on the REQUEST_URI.
What about using http_build_query? http://php.net/manual/en/function.http-build-query.php
It will allow you to build a query string from an array.
I'd use parse_str:
$query = 'q=some&s=3&d=new';
parse_str($query, $query_parsed);
$query_parsed['q'] = 'foo-bar';
$new_query = implode('&', array_map(create_function('$k, $v',
'return $k."=".urlencode($v);'),
array_keys($query_parsed), $query_parsed));
echo $new_query;
Result is:
q=foo-bar&s=3&d=new
Although, this method might look like "the hard way" :)

How to use less variables with $_GET

I've noticed that instead of using:
http://yoursite.com/index.php?page=4
I could just use:
http://yoursite.com/index.php?4
How to do this in php and JavaScript?
In the example you have posted, now 4 is the key instead of value.
If you are passing ONLY one parameter via query string this is doable,otherwise you wont know in PHP what is what without a key for your parameter.
In the particular example you can get it like this in PHP
$id = null
if(!empty($_GET)){
$keys = array_keys($_GET);
// verify that the first key contains only digits, and use it as id
// ctype_digit does not work here because the key is now an int so use is_numeric
if(is_numeric($keys[0]))
$id = $keys[0];
}
I do not know what do you want to do in Javascript here.
Also if you are trying to generate SEO friendly URLs I would suggest that you look into URL Rewriting.
$page = $_SERVER['QUERY_STRING'];

Categories