PHP to check if a URL contains a query string - php

This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can't find a solution for determining if URL does or does not have a query at all.
Using PHP, I simply want to check to see if the current URL has a query string. For example: http://abc.com/xyz/?key=value VS. http://abc.com/xyz/.

For any URL as a string:
if (parse_url($url, PHP_URL_QUERY))
http://php.net/parse_url
If it's for the URL of the current request, simply:
if ($_GET)

The easiest way is probably to check to see if the $_GET[] contains anything at all. This can be done with the empty() function as follows:
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
echo "Hey! Here are all the variables in the URL!\n";
print_r($_GET);
}

parse_url seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with
return strpos($url, '?') !== false;
Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url.

Like this:
if (isset($_SERVER['QUERY_STRING'])) {
}

Related

Extending stripos($_SERVER['REQUEST_URI'] to check for more URLs

I am using stripos to modify an active navigation class,
<?php if (stripos($_SERVER['REQUEST_URI'],'/members/login') !== false) {echo 'class="active"';} ?>
It works like a charm. However I need to add another REQUEST_URI to check in the string and cannot figure out how to properly format the code.
I have tried:
, '/members/login | /members/members'
and others without success.
You'll just have to do it twice:
if(
stripos($_SERVER['REQUEST_URI'],'/members/login') === 0
||
stripos($_SERVER['REQUEST_URI'],'/members/members') === 0){ ...
Note that I switched to ===0 as I presume you wouldn't want '/someotherpartofyoursite/members/members' to match presumably. If you want it in 1 call, you can use regular expressions (see preg_match()), but this is fast & clear enough in my opinion.
If the list becomes longer, it depends on whether these are the whole paths, and if they are, something like this could be more suitable:
$urls = array('/members/login','/members/members');
if(in_array(parse_url($_SERVER['HTTP_REQUEST_URI'], PHP_URL_PATH),$urls)){....
... but not knowing your url scheme that's a guess.
You can do that in single call to preg_match as well like this:
if (preg_match('#/members/(?:login|members)#i', $_SERVER['REQUEST_URI'])) {
// matched
}

PHP - Looking at the Web Link

I am very curious on how to do this. I want a PHP script to look at the string after the URL link and echo the value.
For example, if I entered:
"http://mywebsite.com/script.php?=43892"
the script will echo the value 43892. I have seen this in most websites, and I think it will be a very useful to have in my application.
Thanks,
Kevin
You mean, something like
http://mywebsite.com/script.php?MyVariable=43892
? Variables provided at the end of the URL like that are available in the $_GET array. So if you visited the above URL and there was a line on the page that said
echo $_GET['MyVariable'];
then 43892 would be echoed.
Do be aware that you shouldn't trust user input like this - treat any user input as potentially malicious, and sanitise it.
echo filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_NUMBER_INT);
The sanitation is because in your example the query string is =43892, not 43892. The filter used "remove[s] all characters except digits, plus and minus sign".
Don't you mean http://mywebsite.com/script.php?43892 ?
You can either use apache URL rewriting or try to extract all entries from $_GET and look a the one which looks like a number or simply doesn't have a value.
Try manually parsing the URL like this
$geturl = $_SERVER['REQUEST_URI'];
$spliturl = explode("?",$geturl);
$get
= explode("=",$spliturl[0]);
echo $get[1];
:)
Before I really answer your question, I just have to say that most sites - at least that I have seen - actually use ?43892, with the =. This is also much easier than using it with = in my opinion.
So, now to the actual answer. You can simply extra the query string using $_SERVER['QUERY_STRING'].
An example:
User requests index.php?12345:
<?php
echo $_SERVER['QUERY_STRING'];
?>
Output:
12345
Note that you can also use something like
<?php
if(substr($_SERVER['QUERY_STRING'], 0, 1) == '=') {
$query_string = substr($_SERVER['QUERY_STRING'], 1);
}else{
$query_string = $_SERVER['QUERY_STRING'];
}
echo $query_string;
to support ?=12345 as well as 12345, with the same result. Note also that ?=12345 would not be available as $_GET[''] either.
The way you usualy use query parameters is by assigning them like http://mywebsite.com/script.php?var1=123&var2=234
Then you will be able to access them by $_GET['var1'] and $_GET['var2'] in your PHP script
I'de recommand parse-url for this. The documentation contains all you (I think) need.

PHP Detect if any URL variables have been set

Hey guys, it's kind of hard to explain but basically I want to detect if any variables have been set through the URL. So with my IF statement all of the following should return true:
http://domain.com/index.php?m=100
http://domain.com/index.php?q=harhar
http://domain.com/index.php?variable=poo&crazy=yes
and all the following return false:
http://domain.com/index.php
http://domain.com/test.php
http://domain.com/no_variables.php
Any ideas?
I would test for QUERY_STRING:
if (!empty($_SERVER["QUERY_STRING"]))
should in effect be no different from checking $_GET, though - either way is fine.
if( !empty( $_GET ) ) {
//GET variables have been set
}
(count($_GET) > 0)
If you want to do it with the exception of (a) variable(s), use this if statement before it checks it:
if (!isset($_GET['getvariable'])) {
if (!empty($_SERVER["QUERY_STRING"])) {
echo "do something";
}
}
If you mean taking a string and checking if it has a query string, you can use parse_url.
If you mean checking if the current request has a query string, you can just check the length of $_SERVER['QUERY_STRING'].
If you mean to get a count of the number of variables parsed from the query string, you can do count($_GET);
isset($_GET['m'])
or if anything, I believe count($_GET) might work.

Check query string (PHP)

I use a query string, for example test.php?var=1.
How can I check if a user types anything after that, like another string...
I try to redirect to index.php if any other string (query string) follows my var query string.
Is it possible to check this?
For example:
test.php?var=12134 (This is a good link..)
test.php?a=23&var=123 (this is a bad link, redirect to index..)
test.php?var=123132&a=23 (this is a bad link, redirect to index..)
I'm not sure I fully understand what you want, but if you're not interested in the positioning of the parameters this should work:
if ( isset($_GET['var']) && count($_GET) > 1 ) {
//do something if var and another parameter is given
}
Look in $_SERVER['QUERY_STRING'].
Similar to Tom Haigh’s answer, you could also get the difference of the arguments you expect and those you actually get:
$argKeys = array_keys($_GET);
$additionalArgKeys = array_diff($argKeys, array('var'));
var_dump($additionalArgKeys);
test.php?a=23?var=123 (this is a bad link, redirect to index..)
In this case, you only have one variable sent, named "a" containing the value "a?var=123", therefore it shouldn't be a problem for you.
test.php?var=123132&a=23 (this is a bad link, redirect to index..)
In this case you have two variables sent, ("a" and "var").
In general you can check the $_GET array to see how many variables have been sent and act accordingly, by using count($_GET).
I think you are trying to get rid of unwanted parameters. This is usually done for security reasons.
There won't be a problem, however, if you preinitalize every variable you use and only use variables with $_GET['var'], $_POST['var'] or $_REQUEST['var'].

match any part of a URL

Can anyone help me figure out how to search a URL and print a class based on its result for example:
http://www.?.com/garden-design.html
What i am trying to achieve is using a switch using PHP mathcing a term of say "garden" after the first trailing slash then it would print a class. If it matched construction it would print a different class. There are only three so i know which words to search for. This doesnt have to be dynamic.
Any help would be appreciated.
If it does not have to be dynamic, you could do it like this:
switch(true)
{
case stripos($_SERVER['REQUEST_URI'], 'garden'):
return 'garden';
break;
case stripos($_SERVER['REQUEST_URI'], 'construction'):
return 'construction';
break;
default:
return 'default';
break;
}
The above is quite explicit. A more compact solution could be
function getCategory($categories)
{
foreach($catgories as $category) {
if stripos($_SERVER['REQUEST_URI'], $category) {
return $category;
}
}
}
$categories = array('garden', 'construction', 'indoor');
echo getCategory($categories);
This will not give you the first word after /, but just check if one of your keywords exists in the requested URI and return it.
You could also use parse_url to split the URI into it's components and work with String functions on the path component, e.g.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
In www.example.com/garden-design.html?foo=bar, this would give you just the part garden-design.html. In your scenario you'd probably still do the stripos on it then, so you can just as well do it directly on the URL instead of parsing it.
I'd have thought that making use of parse_url would probably be a good starting point - you could then explode the path component and then do simply strpos comparisons against the three strings you're looking for, if a simple switch statement isn't sufficient. (Be sure to check for !== false if you go down the strpos route.)
This would potentially be faster than a regex based solution.
You can try a regular expression:
/http://www..+.com/(garden|construction|indoor)(-design)?.html/
then $1 would give you garden, construction or indoor as string.
you can also use (.+) to collect any string at that spot.
Update made "-design" optional.
Take a look at the php function strpos(). With it you could do something like:
$url = "http://www.nothing.com/garden-design.html";
if (strpos($url, "/garden-design.html"))
doSomething();
else if (strpos($url, "/construction-design.html"))
doSomethingElse();
else if (strpos($url, "/indoor-design.html"))
doSomethingElseInstead();
String matching is generally quicker and more efficient than regular expressions.

Categories