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
}
Related
So, I am writing a function that receives two arguments, and before I do anything with these variables, I want to check if they are not null.
if (!is_null($foo) && !is_null($bar)) {
/* do something */
}
The problem is that I think we are repeating code, and in some cases when the variable name is a little bit bigger, it becomes painful to write every time.
So, there is a way to shorten this code?
You can use isset which returns FALSE if variable is null. You can set there a lot of variables so code will be shorter:
if (isset($foo, $bar))
You can write your own function to check this:
function is_any_null() {
$params = func_get_args();
foreach($params as $param) {
if (is_null($param))
return true;
}
return false;
}
Now you can use it like this:
if (!is_any_null($foo, $bar)) {
/* do something */
}
is_null() checks a variable to determine if the value is NULL. It can be used in an if statement. It depends on what you would like to do in that if statement. For example, if you would like to do an echo, you can make it a bit shorter using the `elvis``operator:
echo (is_null($foo) && is_null($bar)) ?: 'The values are not null';
Or you could make it a one liner by leaving the { and } out of your code and putting everything on one line.
if (!is_null($foo) && !is_null($bar)) die("NULLLLL");
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');
?>
This is probably the dumbest question out there and the answer is probably NO, but...
Is it possible to use the value of a string in the expression of an if statement? For example, say I pass
'if strcasecmp("hello", "Hello") == 0'
to a function and call it $string, could I then use that value as the conditional evaluation of an if statement?
if (the value of $string) {}
I know eval() will execute a string as if it was PHP code, but actually executes it and returns null/false, rather than just allowing the PHP surrounding the string to deal with the contents of string. I also know you can use variable variables by using ${$varname} that will tell php to use the value of $varname as the name of a a variable.
So I guess what I'm looking for is kind of like 'variable code' instead of 'variable variables'.
I must guess a bit, maybe you want to return from eval?
if (eval('return strcasecmp("hello", "Hello") == 0;')) {}
Also, there are closures that might add a bit more fluidity:
$if = function($string) {
return eval(sprintf('return (%s);', $string));
}
$string = 'strcasecmp("hello", "Hello") == 0';
if ($if($string)) {
...
}
The if statement does not return anything, so your example won't work. However, you can store the expression as a string and eval it later:
$expr = 'strcasecmp("hello", "Hello") == 0';
$val = eval($expr);
Now, keep in mind that using eval is extremely discouraged, as it can lead to serious security problems.
if( eval("return ({$string});") ):
...
endif;
Though what you're trying to do is very bad.
I'd like to use a variable like $GET[name] that always outputs a MySQL-safe version of $_GET[name], even if the value of $GET[name] changes somewhere in the script.
So:
$_GET[name] = "Timmy O'Toole";
echo $GET[name]; // Timmy O\'Toole
$_GET[name] = "Tommy O'Toole";
echo $GET[name]; // Tommy O\'Toole
Is this doable? If not, can you think of any other way that might work that doesn't involve an actual function call? (I'd like to be able to use the variables inside strings and have them automatically evaluate, rather than having to do a whole lot of concatenation.)
Update:
I used a version of mario's solution, and it seems to work:
// Assume $_REQUEST['name'] = "Timmy O'Toole";
class request_safe_vars IMPLEMENTS ArrayAccess {
var $array = array();
function offsetGet($varname) {
return mysql_real_escape_string($_REQUEST[$varname]);
}
function offsetSet($name, $value) { }
function offsetUnset($name) { }
function offsetExists($name) { }
}
$REQUEST = new request_safe_vars();
$_REQUEST['name'] = $_REQUEST['name'].' MODIFIED';
$query = "SELECT id FROM user WHERE name = '{$REQUEST['name']}'";
// Query output:
// SELECT id FROM user WHERE name = 'Timmy O\'Toole MODIFIED'
You don't want to do this.
Rather, the thing you're trying to do -- ensure that the database gets only sane values -- is correct, but the way you're going about it is a bad approach.
Instead of escaping all input as it comes in, you should escape it when you use it by choosing a database adapter that has this functionality built in. PDO is a great example of such a database adapter. PDO uses prepared statements and parameter binding to automatically escape and quote input. Here's an example that binds placeholders at execution time:
$statement = $pdo->prepare('SELECT id FROM users WHERE name = ?');
$statement->execute(array( $_GET['name'] ));
if($statement->rowCount() > 0) {
echo "I found you!";
} else {
echo "You don't exist. :(";
}
Prepared statements with placeholders and binding is the most sane and safe way to ensure that SQL is safe from attack.
That's doable with an object that implements ArrayAccess. By turning $GET into an object you can have a magic offsetSet and offsetGet method which can accomplish this.
class safe_vars IMPLEMENTS ArrayAccess {
var $array = array();
function offsetGet($varname) {
return mysql_real_escape_string($this->array[$varname]);
}
function offsetSet($name, $value) {
$this->array[$name] = $value;
}
function offsetUnset($name) { }
function offsetExists($name) { }
}
This is how you would use it:
$GET = new safe_vars();
$GET["name"] = "Timmy O'Toole";
echo $GET["name"]; // Timmy O\'Toole
I actually have something similar (but never implemented the set part) which specifically works on $_GET (as listed in your question). http://sourceforge.net/p/php7framework/svn/60/tree/trunk/php7/input.php?force=True - It can be configured to apply the sql filter per default for example. Though that approach feels a bit like magic_quotes even if it uses the correct escaping function.
First off, put quotes around 'name' unless you purposely define it as a constant.
Another suggestion would be to use a DB wrapper class such as PDO, mysqli, or your own, and use prepared statements and have the input escaped for you. This has the benefit of escaping data at the last possible time, which is optimal. Either that or you can create a very simple wrapper function, e.g.
function get($key) {
return isset($_GET[$key]) : mysql_real_escape_string($_GET[$key]) : null;
}
The problem with defining a class (unless you use it only statically) is that this strips $_GET of its superglobal status and you are forced to use either globals (evil) or pass all get arguments to local closures.
The code below is just a sample of the format I have
isset($_GET['ids'])?$ids=$_GET['ids']:null;
isset($_POST['idc'])?$idc=$_POST['idc']:null;
function ShowCart()
{
$que = "SELECT
FROM
cart
LEFT OUTER JOIN ...
ON ...
LEFT OUTER JOIN... ON...
WHERE ";
$result = mysql_query($que);
while(){
if (isset($ids)) {
display something
for (){
if(){
} // end of if inside the for loop
}// end of for loop
}
elseif($idc && $ids=null) {
display something different
}
else{
display nothing has passed
}
}//end of while loop
}//end of showcart(); function
that's the formatting above I wonder why the if and elseif are not getting the isset() as the if and elseif argument.
I have debug the through the whole code and the print_r of GET and POST has values through the whole code.
print_r($_POST);
print_r($_GET);
Jona, if you'd ever bother to properly format your code, you'd see that the 'else' in question is WITHIN A FUNCTION, and you're defining $ids and $idc OUTSIDE THE FUNCTION. Remember, in PHP, global variables (except the super-globals, such as $_GET, $_POST, etc...) are not visible within functions unless you explicity define them as globals within the function.
Add global $idc, $idc; as the first line in the function definition and your if() will start working correctly.
Followup:
Your code is still hideously formatted, and very wonky. Take this:
isset($_GET['ids'])?$ids=$_GET['ids']:null;
You're using a trinary operator, but not assigning its results anywhere, and using the 'true' condition to do an assignment. This is an ugly hack. It should be written like this:
$ids = isset($_GET['ids']) ? $_GET['ids'] : null;
This way $ids will be set to null if there is no $_GET['ids']. Which brings up the fact that you're assigning a null instead of some other default value. If there really was no $_GET['ids'], then this:
$idx = $_GET['ids'];
would work identically, as PHP will automatically assign a null in situations where the right-hand-side doesn't exist. Of course, you still have to sanitize this value, since you're using it in an SQL query later on. Leaving it like this will just invite SQL injection attacks and all kinds of other abuses.
Beyond that, you're still creating $ids and $idc OUTSIDE of your ShowCart() function. As such, $ids and $idc within the function will be automatically be created with null values, since you've not declared them to be global. I think by now it's obvious you have no idea what this means, so try out this piece of code:
<?php
$var = 'Here I am!';
function showVar() {
echo "Within showVar(), var is set to: $var\n";
}
function workingShowVar() {
global $var;
echo "Within workingShowVar(), var is equal to: $var\n";
}
showVar();
workingShowVar();
If you copy/paste this code, run it, you'll see the following output:
Within showVar(), var is set to:
Within workingShowVar(), var is set to: Here I am!
Notice that both functions are identical, except for the global declaration. If you can figure out the difference, then you'll realize you need to re-write your ShowCart() function as follows:
function ShowCart() {
global $ids, $idc;
// rest of your code here
}
Well the code you've posted is sound, so it's probably a problem with the variables getting to that script in the first place. Are you sure those variables are defined in the GET string?
Dump out the contents of it to make sure:
print_r($_GET);
Try this:
$ids= isset($_GET['ids'])?intval($_GET['ids']):null;
$idc= isset($_GET['idc'])?intval($_GET['idc']):null;
if (isset($ids)) {
//display something
}
elseif(isset($idc)) {
//display something different
}
else
{
//display nothing has passed
}
I tested your script above,it works as expected.Maybe you should check whether the link is correct or not.