Checking variables using the eval()-Function - php

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

Related

multiple !isset() with OR conditions in php

if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
My Other Tries:
(!isset($_GET['new_quiz'] || $_GET['view_quiz'] || $_GET['alter_quiz']))
( ! ) Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in
C:\wamp\www\jainvidhya\subdomains\teacher\quiz.php on line 94
(!isset($_GET['new_quiz'],$_GET['view_quiz'],$_GET['alter_quiz']))
NO
You may find than inverting the logic makes the code easier to read, I also like to have a more positive idea of conditions as it can read easier (rather than several nots means no).
So this says if anyone of the items isset() then the answer is Yes...
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo "Yes";
}
else{ echo "No"; }
Note that I've changed the Yes and No branches of the if around.
You are probably looking for
if(!isset($_GET['new_quiz']) && !isset($_GET['view_quiz']) && !isset($_GET['alter_quiz'])){
echo "No";
}
else {
echo "Yes";
}
which will print Yes if none of new_quiz, view_quiz and alter_quiz are present in the URL. If this is not your desired outcome, please elaborate on your problem.
#paran you need to set a value for view_quiz=yes for example
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
and the url
index.php?new_quiz=yes
index.php?view_quiz=yes
index.php?alter_quiz=yes
All Will return true
isset()allows multiple params. If at least 1 param does not exist (or is NULL), isset() returns false. If all params exist, isset() return true.
So try this:
if( !isset( $_GET['new_quiz'], $_GET['view_quiz'], $_GET['alter_quiz']) ) {
First, to answer your question:
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
This is becaue this
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
checks if either one of your parameter is not set, which will always be the case as long as you are not setting all three parameter simultaneously like this:
index.php?alter_quiz&view_quiz&new_quiz
As #nigel-ren stated, you may wan't to change that logic to
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo 'Yes';
which checks if at least one parameter is set.
If you wan't to check if there is only one of the three parameters set, you would have to work with XOR (which is slightly more complicated)
$a = isset($_GET['new_quiz']);
$b = isset($_GET['view_quiz']);
$c = isset($_GET['alter_quiz']);
if( ($a xor $b xor $c) && !($a && $b && $c) ){
echo 'Yes';
(based on this answer: XOR of three values)
which would return true if one and only one of the three parameters is set.
But - and this is just an assumption, please correct me if I'm wrong - I think what you are trying to achieve are three different pages (one for creating a quiz, one for viewing it and one for editing it). Therefore, you will likely run into a problem with your current setup. For example: What would happen if a user calls the page with multiple parameters, like
index.php?alter_quiz&view_quiz
Would you show both pages? Would you ignore one parameter? I would recommend to work with a single parameter to avoid this problem in the first place. For example site which can take the values alter_quiz, view_quiz or new_quiz. E.g.:
index.php?site=alter_quiz
Then you can work like this:
// check if site is set before getting its value
$site = array_key_exists( 'site', $_GET ) ? $_GET['site'] : NULL;
// if it's not set e.g. index.php without parameters is called
if( is_null($site) ){
// show the start page or something
}else{
$allowed_sites = ['new_quiz', 'view_quiz', 'alter_quiz'];
// never trust user input, check if
// site is an allowed value
if( !in_array($site, $allowed_sites, true) ){
die('404 - This site is no available');
}
// here you can do whatever your site should do
// e.g. include another php script which contains
// your site
include('path/to/your/site-' . $site . '.php');
// or echo yes
echo 'Yes';
}

PHP take string and check if that string exists as a variable

I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>

Tricky verification code on a form

I have an implemented control check on a form coded this way:
public function checkCittaResidenza() {
if (is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45 || strlen($this->citta_residenza == 0))) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
}
In this version, it simply checks if it is a string and check its lenght that should be less than 45 chars. It puts the string in an array corretti() if positive, else it initialize an error message specified above in an abstract class parent of the checking class.
What i'd love it to do is:
1) make a check on the string to see if it's not null.
2) if it's not null, do the check (that could be even more particular than the simple one shown here, but i don't have problems on this), put it in corretti() if correct and initializing the error if it's not, as the code now says.
3) if the string is null, the program should skip the check and directly write the null value into the array corretti(), because the form is imagined to be completed in different steps over the time, so it always happen that it's not fully filled.
I'm having problem on coding the if cycle for this last condition, every cycle i tried and imagined puts the empty condition as a cause for initializing an error.
Thank you!
Try this,
public function checkCittaResidenza() {
if(isset($this->citta_residenza)){
if ((is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45) || $this->citta_residenza == "")) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
} else {
$this->corretti['citta_residenza'] = "null";
}
}

Checking for a null value in conditional in PHP

I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}

Better way to check variable for null or empty string?

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. The following things are considered to be empty
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

Categories