If-statement in a Variable - php

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';
}

Related

Checking variables using the eval()-Function

I have a list of variables (var1, var2, ...). Now I'd like to check these variables using several conditions and print out an error message if the condition is true.
As there are many "checks" that should be done I saved the "conditions" in a MySQL-DB (varchar):
condition errormsg
--------------------------------------------------------
$var1!=1 && $var1!=2 var1 should be 1 or 2
$var1=='' var1 is missing
$var3<0 & $var3>10 var3 should be between 0 and 10
Now I'd like to check these variables using the eval-Function:
$res=mysqli_query($con, "SELECT * FROM conditions");
while($row=mysqli_fetch_object($res)){
if(eval($row->condition))
echo $row->errormsg;
}
Can this work or is there a better solution without eval()? Thank you for your help!
Many people suggest to get alternate of this . But if you really need this you can do this way. I don't have your data so I have made this with my own way
<?php
$condition = "1!=1";
//$condition = "1==1";
$error = "test";
eval("\$con = $condition ;");
if($con){
echo $error;
}else {
echo "not found";
}
?>
Uncomment second line to get another change. Just keep in mind that statement should be complete in eval function.
Live demo : https://eval.in/847626
Pay special attention not to pass any user provided data into it without properly validating it beforehand.
The common solution for your problem is to write validation functions for the variables. Such a function receives a variable as argument, checks its value and return either success or an error code. Then the calling code uses the error code to lookup the error message in the list of localized strings for the current language.
It could be like below:
The validation functions
function var1_is_valid($var1)
{
if ($var1 == 1 || $var1 == 2) {
return 'SUCCESS';
} else {
return 'ERR_VAR1_INVALID';
}
}
function var1_is_present($var1)
{
if ($var1 != '') {
return 'SUCCESS';
} else {
return 'ERR_VAR1_MISSING';
}
}
function var3_is_valid($var3)
{
if (0 <= $var3 && $var3 <= 10) {
return 'SUCCESS';
} else {
return 'ERR_VAR3_INVALID';
}
}
The language file(s)
// Use the strings returned by the validation functions as keys in the array
$lang = array(
'ERR_VAR1_INVALID' => 'var1 should be 1 or 2',
'ERR_VAR1_MISSING' => 'var1 is missing',
'ERR_VAR3_INVALID' => 'var3 should be between 0 and 10',
);
Even better, you can combine the functions var1_is_valid() and var1_is_present() into a single validation function for $var1 that returns either 'SUCCESS' or the appropriate error string.
All the error messages for a language stay in a single language file that is loaded on each request. It works faster than querying the database for the error messages.
Another language means another file with strings identified by the same keys. You won't use two language on the same time. At most, you load the language that is completely implemented before loading the language requested by the user, in order to have a value for each string (a message in the wrong language is still better than nothing).
You can use a pseudo-switch, eliminating the need for a db and eval(). Minimalistic example:
$var = 1;
switch(true){
case ($var == 1):
echo "1\n";
case ($var != 2):
echo "2\n";
}

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

How to dynamically pass condition of if statement

I am in a situation where I'll get comparison string in a variable, and I want to use that variable in IF
$xyz = '$abc<200'; // Dummy Dynamic Text
if($xyz) { // It should execute like if($abc<200)
echo 'you are dynamic';
}
In the example above the comparison string coming dynamically in $xyz variable and I want to put that variable in if condition, How do I do that?
You cannot use quotes as it is making the string out of it. Do it this way:
$xyz=($abc<200); //or, as well, $xyz=$abc<200
if($xyz) {
echo 'you are dynamic';
}
If however you want to keep that condition text in string, you could use eval:
$xyz='$abc<200';
if(eval("return $xyz;")) {
echo 'you are dynamic';
}
Eval is sometimes disabled. This is for security reasons. Often with suhosin. Eval can be evil! Think about code injections.
You could try to use an anonymous function.
<?php
$func = function($abc) {
return $abc<200;
};
if ($func($abc)) {
// great
}

understading the ternary operator in php

I'm reading someone else's code and they have a line like this:
$_REQUEST[LINKEDIN::_GET_TYPE] = (isset($_REQUEST[LINKEDIN::_GET_TYPE])) ? $_REQUEST[LINKEDIN::_GET_TYPE] : '';
I just want to make sure I follow this. I might have finally figured out the logic of it.
Is this correct?
If $_REQUEST[LINKEDIN::_GET_TYPE] is set, then assign it to itself. (meant as a do-nothing condition) otherwise set it to a null string. (Would imply that NULL (undefined) and "" would not be treated the same in some other part of the script.)
The ternary operator you posted acts like a single line if-else as follows
if (isset($_REQUEST[LINKEDIN::_GET_TYPE])) {
$_REQUEST[LINKEDIN::_GET_TYPE] = $_REQUEST[LINKEDIN::_GET_TYPE];
} else {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
Which you could simplify as
if (!(isset($_REQUEST[LINKEDIN::_GET_TYPE]))) {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
You missed the last part. If $_REQUEST[LINKEDIN::_GET_TYPE] is not set, then $_REQUEST[LINKEDIN::_GET_TYPE] is set to empty, not null. The point is that when $_REQUEST[LINKEDIN::_GET_TYPE] is called, that it exists but has no value.
Think of it this way
if(condition) { (?)
//TRUE
} else { (:)
//FALSE
}
So,
echo condition ? TRUE : FALSE;
if that makes sense
This
$foo = $bar ? 'baz' : 'qux';
is the functional equivalent of
if ($bar) { // test $bar for truthiness
$foo = 'baz';
} else {
$foo = 'qux';
}
So yes, what you're doing would work. However, with the newer PHP versions, there's a shortcut version of the tenary:
$foo = $bar ?: 'qux';
which will do exactly what you want
Your explanation is correct as far as my knowledge goes.
A ternary operator is like an if statement. The one you have would look like this as an if statement:
if( isset($_REQUEST[LINKEDIN::_GET_TYPE] ) {
$_REQUEST['LINKEDIN::_GET_TYPE] = $_REQUEST['LINKEDIN::_GET_TYPE];
} else {
$_REQUEST['LINKEDIN::_GET_TYPE] = ''; // It equals an empty string, not null.
}
Sometimes its easier to look at a ternary statement like a normal if statement if you are unsure on what is going on.
The statement you have seems to be doing what you say, setting the value to its self if it is set, and if it is not set, setting it to an empty string.

"if else statement" when no $_REQUEST exist

I am making a simple if and else statement to get value from a requested link my code is
if($_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
and suppose the link is www.example.com/profile.php?f_id=3
now its simple as if the f_id is empty or with value either of the above if and else statement would run. but what is a user is just playing around with link and he removes the whole ?f_id=3 with link left to be opened with www.example.com/profile.php then how to detect that f_id dosen't exist and in that case redirect to a error page ?
if ( isset( $_REQUEST['f_id'] ) ) {
if($_REQUEST['f_id']=='') {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}
} else {
REDIRECT TO ERROR PAGE
}
UPDATE Since your URLS-s look like www.example.com/profile.php?f_id=3 you should use $_GET instead of $_REQUEST
you can use the isset() php function to test that:
if(!isset($_REQUEST) || $_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
Late answer, but here's an "elegant" solution that I always use. I start with this code for all the variables I'm interested in and go from there. There are a number of other things you can do with the extracted variables as well shown in the PHP EXTRACT documentation.
// Set the variables that I'm allowing in the script (and optionally their defaults)
$f_id = null // Default if not supplied, will be null if not in querystring
//$f_id = 0 // Default if not supplied, will be false if not in querystring
//$f_id = 'NotFound' // Default if not supplied, will be 'NotFound' if not in querystring
// Choose where the variable is coming from
extract($_REQUEST, EXTR_IF_EXISTS); // Data from GET or POST
//extract($_GET, EXTR_IF_EXISTS); // Data must be in GET
//extract($_POST, EXTR_IF_EXISTS); // Data must be in POST
if(!$f_id) {
die("f_id not supplied...do redirect here");
}
You could use empty to combine the 2x isset into 1 statement (unless you actually have a friend_id of 0 which would result in empty being true)
if(empty($_REQUEST['f_id'])) {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}

Categories