PHP check if url parameter exists - php

I have a URL which i pass parameters into
example/success.php?id=link1
I use php to grab it
$slide = ($_GET["id"]);
then an if statement to display content based on parameter
<?php if($slide == 'link1') { ?>
//content
} ?>
Just need to know in PHP how to say, if the url param exists grab it and do the if function, if it doesn't exist do nothing.
Thanks Guys

Use isset()
$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
EDIT:
This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.
$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

if(isset($_GET['id']))
{
// Do something
}
You want something like that

Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:
Change your first line to
$slide = '';
if (isset($_GET["id"]))
{
$slide = $_GET["id"];
}

I know this is an old question, but since php7.0 you can use the null coalescing operator (another resource).
It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.
$slide = $_GET["id"] ?? 'fallback';
So if $_GET["id"] is set, it returns the value. If not, it returns the fallback. I found this very helpful for $_POST, $_GET, or any passed parameters, etc
$slide = $_GET["id"] ?? '';
if (trim($slide) == 'link1') ...

Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.

Related

Dynamic keyword insertion

I'm using this code to pass some information from my url to my webpage.
mysite.com/?v=keyword
My problem is I need a default keyword when traffic goes to my site and the referring link is not passing information from the url.
I need a default keyword if no information is passed. Can anyone help me.
The default should be set in your PHP file. You can use a ternary operator based on isset(). If the condition is true, the first value (after ?) will be used, if the condition is false, the second value (after :) will be used.
$keyword = (isset($_GET['v'])) ? $_GET['v'] : 'default';
This is equivalent to:
if (isset($_GET['v'])) {
$keyword = $_GET['v'];
}
else {
$keyword = 'default';
}
<?php
if(isset($_GET['v'])){
$keyword = htmlspecialchars($_GET['v']);
}else{
$keyword = "Something" ;
}
echo "<a href='http://somesite.com/?$keyword'>$keyword</a>";
?>
Learn more about isset()
Alternatively you can use !empty (not empty)
<?php
if(!empty($_GET['v'])){
$keyword = htmlspecialchars($_GET['v']);
}else{
$keyword = "Something" ;
}
echo "<a href='http://somesite.com/?$keyword'>$keyword</a>";
?>
Learn more about empty()

PHP, easier way to get array values without warnings

Dudes,
is there a more concise way to write the statement below? If I don't check if an array key exists I get a PHP warning. However, the below is a bit too, ehm, wordy.
Thanks!
$display_flag = false;
if (array_key_exists('display_flag',$pref_array) {
$display_flag = $pref_array['display_flag'];
}
Since PHP 7 you can use the new null coalescing operator.
$display_flag = $pref_array['display_flag'] ?? false;
If $display_flag is a boolean:
$display_flag = isset($pref_array['display_flag']) && $pref_array['display_flag'];
If it's a string:
$display_flag = isset($pref_array['display_flag']) ? $pref_array['display_flag'] : false;
// Get the $pref_array from wherever
$default_prefs = array(
"display_flag" => false,
);
$pref_array = array_merge($default_prefs, $pref_array);
// Now you know it's always defined with default values
The way you have it is fine, as you should validate if the value actually exists, but you could also do a ternary op:
$display_flag = (isset($pref_array['display_flag'])) ? (bool) $pref_array['display_flag'] : false;
I typecast the contents of display_flag to bool if it is set, so you are ensured a boolean value in either case.
Also you could (but I don't recommend it), squelch the warning with the #:
$display_flag = #$pref_array['display_flag'];
Another simpler option is:
array_get($variable, 'keyName', null)
The third argument is the default value.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);

Php pages dependent on query string but what if there's no parameter?

I am creating pages that are dependent on a query in the url (eg europe.php?country=france). I am aware that it will be useful to re-write theses as europe.php/france with htaccess for SEO etc but what if that page is accessed without the query string?
I am using php to $_GET the query, so if I access the page without the query I get 'var=;' ie, it is empty (and retrieves an error). I'm trying to use an if statement to check if the $_GET retrieves nothing but am unsure if this is the right thing to do.
So: how do I check for an un-retrieved var so I can set a default?
Or: am I going about this the wrong way?
If you know the index into $_GET, use isset():
$country = 'default';
if( isset( $_GET['country'])) {
$country = $_GET['country'];
}
This will only test if the country parameter was passed, but it could have been set to an empty string. If this is invalid input, you can combine the check using empty():
$country = 'default';
if( isset( $_GET['country']) && !empty( $_GET['country'])) {
$country = $_GET['country'];
}
You can condense this into one line and save the result to a variable $country using the ternary operator, like so:
$country = (isset( $_GET['country']) && !empty( $_GET['country'])) ? $_GET['country'] : 'default';
Finally, you can check if you got absolutely no $_GET parameters by calling count() on $_GET:
if( count( $_GET) == 0) {
die( "No parameters - Invalid input!");
}
since isset() really tests for "NOT NULL", you should use empty() to test if an empty string was given:
if (empty($_GET['country'])) {
$_GET['country'] = "default";
}
that is, unless you expect 0 to be a valid input, in that case, you'd have to check with isset and make sure the string has at least one character:
if (!isset($_GET['country']) || !strlen($_GET['country'])) {
$_GET['country'] = "default";
}
which can be optimized into
if (!isset($_GET['country']) || !isset($_GET['country'][0])) {
$_GET['country'] = "default";
}
try using something like this:
$var = ( isset($_GET['var']) ? $_GET['var'] : 'default value' )
Try doing this
if(isset($_GET['your_variable'])) {
$variable = $_GET['your_variable'];
} else {
$variable = "not set";
}
That will set the variable if it is set in your URL - or it can set your variable to some other value if it is not set in the URL
Running a check at the start of the page to see if var is set is fine to do. If it's empty, you can redirect using something like:
header("HTTP/1.0 404 Not Found");
header('Location:YOUR PAGE NOT FOUND PAGE');
exit();
On a side note, if you're using data from $_GET, you need to make sure that this data is validated & cleaned to prevent against all sorts of security intrusions, such as XSS and, if you use a database, MYSQL injection. Running a test at the start of the page to check if it's empty can be just the start - you can also make sure that the data is something you'd expect (say, check it's alphanumeric). After, with $_GET data, anyone could fill the URL bar with whatever they like and potentially damage your website.
Hope this has helped!

Check if $var = anything in an array?

I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:
$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);
--
$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1
--
if ($post_count= //any value in $posts_ev4) :
echo 'this'
else :
NULL;
endif;
I have been able to make this work using the or operator but I end up with very long blocks of code.....
if (($post_count=1) || ($post_count=2)) :
echo 'this'
else :
NULL;
endif;
I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.
Try:
if (in_array($post_count, $post_ev4)) {}
See: in_array()
Use in_array() to check if value exists in array.
if (in_array($post_count, $posts_ev4)) :
echo 'this'
else :
NULL;
endif;
Check out the isset() function in the PHP Manual.
There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.
if(is_array($array) && in_array($post_count,$array))
{
// do operation
}

Categories