PHP - Get part of $_GET string - php

I currently have this:
$thispage = $_SERVER['QUERY_STRING'];
if($thispage == "i=f" || $thispage == "i=f&p=t" ) echo "active";
Although, the "i=f&p=t" is not correct, as the page looks like this:
i=f&p=t&cid=71&id=161
My question is, how can I do so if just the first part of the $_GET string is correct (in this example "i=f&p=t) then it will match $thispage. I don't want it to check for & $_GETs
I want $thispage to work with other pages than just the example above. I only want to check the first part of the string. Not what comes after &

I'd go for parse_str function:
parse_str($_SERVER['QUERY_STRING'], $thispage);
if ( $thispage['i'] === 'f' OR ($thispage['i'] === 'f' AND $thispage['p'] === 't') ) {
echo 'active';
}
Update:
I don't want it to check for & $_GETs
I don't know why you don't want to use $_GET if it's the Query String that you're working on that now, but you can do the following as well, which makes more sense:
if ( $_GET['i'] === 'f' OR ($_GET['i'] === 'f' AND $_GET['p'] === 't') ) {
echo 'active';
}

Did you mean this?
if(strpos($_SERVER['QUERY_STRING'], 'i=f') !== false) {
echo "active";
}

If that is truly what you want to do, then you are actually checking if
if (substr($_SERVER['QUERY_STRING'], 0, 7) === "i=f&p=t")

You can access the url parameters directly by using the $_GET array.
var_dump($_GET);
If you want to use $_SERVER['QUERY_STRING'] you can use the parse_str function to parse the query string:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>

Related

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

working with 3 $_GET values

I have a problem with $_GET array. On my page a value comes from URL like this.
http://localhost/search.php?subject=Mathematics
I check this $_GET value something like this..
// Check for a valid keyword from search input:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
foreach ( $_GET AS $key => $subject) {
$searchKey = $key;
$searchKeyword = '%'.$subject.'%';
}
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Now its working for me. But my problem is I am using another two variables to pass through URL on same page to filter my database values.
echo '<li>Tutor</li>
<li>Institute</li>';
This two links I used to filter my database values (clicking on this link).
$tutor = isset($_GET['institute']) ? '0' : '1';
$institute = isset($_GET['tutor']) ? '0' : '1';
My problem is when I am trying filter database result clicking on the above link its always going this code instead of displaying filtered result.
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Can anybody tell me how I use this 3 $_GET values.
Why not just add a clause in the else:
elseif(!isset($_GET['institute']) && !isset($_GET['tutor']))
{
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
You need to make sure the url looks like this:
http://localhost/search.php?subject=Mathematics&tutor=tutorName&institute=instituteName
A ? denotes the beginning of the URL parameters, an & marks the separation between url parameters
Your problem doesn't seem to be, that you're running into the else loop (or better said: not the only problem). It looks like your first parameter gets lost with the second link. I think, the second link should react like some kind of extended search filter, that shoud be applied to the recently displayed content, or am I totally wrong at understanding you?
Perhaps this could solve your problem for creating the follow-up URLs.
$params = array();
foreach($_GET as $key => $value) {
$params[] = '&'.$key.'='.$value;
}
$url1 = '?tutor=link'.implode('', $params);
$url2 = '?institute=link'.implode('', $params);
And when you output the links:
echo '<li>Tutor</li>
<li>Institute</li>';
Your problem is that you are only checking the $_GET['subject'] variable, which is no being passed in. You could do this in a few ways, all resulting in changing:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
1) include all variables in the conditional string:
if ( ((isset($_GET['subject'])) && (is_string ($_GET['subject']))) || ((isset($_GET['institute'])) && (is_string ($_GET['institute']))) || ((isset($_GET['tutor'])) && (is_string ($_GET['tutor']))) ) {
2) Pass in searchKey=1 or something in all your links and use:
if ( isset($_GET['searchKey']) ) { // From SESSION
Revised links:
echo '<li>Tutor</li>
<li>Institute</li>';
If you are looking to pass in more than one variable at once, you will need to put the search keys into an array.

How do I write this PHP string that has an equal sign within it?

<?
$xm="1?x=1";
if($_GET["x"]=="1" || $_GET["x"]=='$xm'){ ?>
String Works
<? } ?>
Basically the URL reads:
http://site.com/shop/category/product?x=1?x=1
This happens when a form is submitted. I do not have access to change it to:
http://site.com/shop/category/product?x=1&x2=1
Change it to:
<?
$xm="1?x=1";
if($_GET["x"]=="1" || $_GET["x"]=="{$xm}"){ ?>
String Works
<? } ?>
If the URL looks like ...product?x=1?x=1, the $_GET array will look like this:
array(1) {
["x"] => string(5) "1?x=1"
}
So your condition just needs to look like:
if ($_GET["x"] == '1?x=1')
Your problem is simply that you quote the variable $xm in single quotes, which literally results in the string "$xm".
Now obviously, that's a rather broken URL. If you don't know how many times ?x=1 will occur in it, it's hard to compare to anything constant.
What you have should work, with the change that '$xm' will not evaluate to "1?x=1":
if (isset($_GET['x']) && ($_GET['x'] == 1 || $_GET['x'] == $xm)) {
echo 'string works';
}
If the argument will always be numeric, you can also just write this to coerce $_GET['x'] into an integer before comparison:
if (isset($_GET['x']) && $_GET['x'] == 1) {
echo 'string works';
}
This works because '1?x=1' == 1, but also '1?x=2' == 1 ... if that's not the desired behavior, do let me know.
use http_build_query whenever you want to build links
equal sign has special meaning in url context. they need to be encoded to treat them like literal value either with urnencode() or rawurlencode() or base64 encode

What is meant by this php statement

Hello I have read following php statement from a blog but I am unable to understand its meaning. Is it treated as if condition or any thing else? Statement is
<?= ($name== 'abc' || $name== 'def' || $name== 'press') ? 'inner-pagehead' : ''; ?>
You can read this as:
if($name=='abc' || $name=='def' || $name=='press') {
echo 'inner-pagehead';
} else {
echo '';
}
The <?= is the echo() shortcut syntax, then the (test)?true:false; is a ternary operation
It is saying that if $name is any one of those 3 values ("abc","def", or "press"), then display the text "inner-pagehead". Otherwise, don't display anything.
This is what I would call a poorly written Ternary condition. it basically echos 'inner-pagehead' if the $name variable matches any of the three conditions. I would have done it like this:
<?php
echo in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
?>
Or, even better:
// somewhere not in the view template
$content = in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
// later, in the view template
<?php echo $content; ?>

How can I add an if statement in a stripos?

how can I keep the p= and add an OR /20 on it ? I mean I want to check both strings.
<?php if ( false==stripos(get_permalink($post->ID), 'p=') ) { ?>
You cannot test for two portions of strings with a single stripos() call : you have to call stripos() twice.
Depending on what you exactly want to achieve (not sure I really undertand the question), you'll combine those two with && or || :
$link = get_permalink($post->ID);
if (stripos($link, 'p=')!==false && stripos($link, '/20')!==false) {
// the link contains both p= AND /20
}
or :
$link = get_permalink($post->ID);
if (stripos($link, 'p=')!==false || stripos($link, '/20')!==false) {
// the link contains p= OR (inclusive) /20
}
As a sidenote : you should use === or !==, as stripos() can return 0 or false -- and those don't have the same meaning.
You have to call it twice:
if( false===stripos(get_permalink($post->ID), 'p=') ||
false===stripos(get_permalink($post->ID), '/20')
) {

Categories