Dynamic keyword insertion - php

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

Related

PHP check if url parameter exists

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.

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!

If-statement in a Variable

I want to print the same page's name differently based on a certain variable.
Here is a corresponding code.
$metaTitle ="'if($variable=='input'){ title#1 }else { title#2 };'";
And the produced meta title is lately used in the same file to create the page title (<title></title>)
But it keeps producing the title like
if($variable=='input'){ title#1 }else { title#2 };
(the whole if statement as a whole. It does not recognize the if statement. It considers the statement as a plain text.)
What did I do wrong in the sentence??
Use ternary operator "?:":
$metaTitle = ($variable=='input')? "title#1" : "title#2";
The first part is the condition:
($variable=='input')
The second is the result when condition is true:
"title#1"
The third is the result when condition is false:
"title#2"
Source http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Because you just assign $metaTitle a STRING "'if($variable=='input'){ title#1 }else { title#2 };'" and it's not a runable statement
you should do like this
if ($variable=='input') {
$metaTitle = "title#1";
} else {
$metaTitle = "title#2";
}
or simply use Ternary Operator
The simplest and most basic solution is to set the title variable inside the if statement.
if($variable=='input'){
$metaTitle = 'title#1';
} else {
$metaTitle = 'title#2';
}
Try this instead -
if($variable=='input')
{
$metaTitle = 'title#1';
}
else
{
$metaTitle = 'title#2';
}

Ternary Operator Question

Can someone give me an example of how to use the PHP ternary operator which will check for a variable using $_GET (which can be defined in the URL), if it's not in the URL then check if the var was set in another PHP file. If it wasn't set in the URL or another PHP file, then I want it to equal "default".
$myVar = isset($_GET["someVar"]) ? $_GET["someVar"] : (isset($someVar) ? $someVar : "default");
$value = isset($_GET['somevar']) ? $_GET['var'] : $default_value;
On the most recent PHP versions, there's a shortcut version of this:
$value = isset($_GET['somevar']) ?: $default_value; (not the same as the first version)
You can use $GLOBALS['nameofvar'] to see if a particular PHP variable has been defined as well, though this'll be problematic if you're doing the check inside a function.
Are you looking for something like this:
if(isset($_GET["MyVar"]))
{
$newVar = $_GET["MyVar"];
}
else if(isset($myVar))
{
$newVar = $myVar;
}
else
{
$newVar = "default";
}
or
$newVar = isset($_GET["MyVar"]) ? $_GET["MyVar"] : (isset($myVar) ? $myVar : "default");

Categories