PHP—Empty String Help - php

The CMS I'm using has a plugin that pulls a series of pages based on how you've tagged those pages. Everything is working fine, but I need to display the number of pages returned after a user sends a query.
The variable that the number of records is stored in is a string. The small script I'm writing tries to check if this string is blank, and if so echo nothing, but if it's not blank echo the number of pages returned.
<?php
if ($count !== ''){
echo "text";
}
?>
However, whenever it's passed when the string is supposed to be empty it treats it as if it is not. I'm not sure what I'm doing wrong or what the string contains that it's not empty.
I found a resource about converting strings to integers but it set it to 0. Thanks for any help.

$count will never be equal to ' ' if you trim it before.

It cannot be equal to ' ' after trim, you should check if it is equal to an empty string and not a string with a white space. (trim deletes white spaces)
trim — Strip whitespace (or other characters) from the beginning and end of a string
http://php.net/manual/en/function.trim.php

trim removes all spaces, so $count == ' ' will always be false if you trimmed first. The easiest change to your code would be to replace the ' ' with ''. Or you could just do this: echo trim($count) === '' ? '' : "text";

trim() is going to remove all white-space characters from the beginning and end of the string. Unless there is content in the middle, you'll likely end up with a completely empty string. If you're testing for this, try checking empty() or is_null().
if (empty($string)) {
echo "String is empty.";
}
I find it's better using built-in functions instead of hard-coding a =='' comparison.

Use var_dump() to check the type and the content of the variable.
Check the manual

Your code seems wrong; you've got "!==", where I'd swear you need to have "!=" (only one equals sign). I'm not sure what "!==" would evaluate to, but I'd bet it's not what you want.

It seems from the comments that your "blank" string is not blank, but instead has something odd in it. Assuming that it's not too odd I'd just try this:
$count = intval($count);
if ($count) {
echo 'text';
}
Though this assumes that the $count actually looks like a number to intval when it's got a number in it -- we may need to take a look at this "string" you're getting back in more detail to figure out what's really in it.
Hopefully you've already taken the advice given by others and looked at the resulting page source after doing a var_dump() -- otherwise I'd guess that $count has XML in it, or something else that won't render well if you dump it to an HTML page and view the page rather than the source...
If nothing else, you could really try brute-forcing it:
$count = intval(preg_replace('/[^\d]/', '', $count));
if ($count) {
echo 'text';
}
...but really it'd be better to work out what this odd plug-in is giving you, and why. Which CMS and plugin is it? Are there some docs available for this thing that's returning $count to you? Do you have the plugin source?

Related

PHP fix zero-width-space inside string variable

I have zipcodes being outputted, coming from user inputted values. Looks like it is outputting zero-width-space \u200b sometimes at the beginning of the strings.
What is the best way to replace these from within php before echoing the variable?
I use this function to trim unicode spaces - this should work in your case too.
function trimUnicode($str) {
return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$str);
}
Ok, seems as though this was coming from the actual string being echo'd by PHP, so I did the following to the string:
$zipcode = trim(utf8_decode($zipcode), '?');
All seems fine now!

Evaluate mathematical operations inside a string using PHP

I want to evaluate a mathematical operations inside the string after I get it in that string.
Here is the string
$string = "Add this two numbers [4+2+2]. And [5*3/2] will result to?"
I already get those numbers:
$f_number = "4+2+2";
$s_number = "5*3/2";
How can I evaluate this automatically using any function?
Sample:
echo anyfunction($f_number);//will result to 8
echo anyfunction($s_number);//will result to 7.5
because if I will echo directly it will just output like this:
echo $f_number;//will result to 4+2+2
echo a$s_number;//will result to 5*3/2
You can use eval. It's probably the easiest way out. Mind though that it can also be used for other expressions, because it basically executes any PHP code that is in the string.
But by wrapping it in a function, like you intended, you can at least black box it, and add safety measures later if you need to, or even switch to a different expression evaluator, without having to change all your code.
A simple safety measure would be to check if the string only contains numeric values, whitespace and allowed operators. That way it should be impossible to secretly inject actual code.
function anyfunction($expr)
{
// Optional: check if $expr contains only numerics and operators
// actual evaluation. The code in $expre should contain a return
// statement if you want it to return something.
return eval("return $expr;");
}
echo anyfunction($f_number);

How to convert string variable to integer in php?

I'm very new to php .I want to convert the string to integer value.
I used following code to convert
$val='(100*2)';
echo (int)($val); //This will showing output as 0
But echo (int)((100*2)); /This will showing output as 200
Please help me any one to solve this .Thanks advance
(int)($val) evaluates to 0 because $val's value is not a numeric string (ie one that can be directly cast to a number).
If you really need this kind of functionality, try eval():
$val='(100*2)';
echo (int)($val); //This will showing output as 0
eval('$newval='.$val.';');
echo $newval;
But be warned: eval() can be dangerous!
From http://php.net/manual/en/function.eval.php:
Caution
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
EDIT: Added .';' to eval parameter to make it a legit php instruction.
The most common suggestion will be - evaluate your string as PHP code, like:
$val = '(100*2)';
eval('$val = '.$val.';');
-but that's unsafe, eval should be avoided as long as possible.
Alternatively, there is bcParser for PHP, which can solve such issues. That's more safe than eval.
Finally, I doubt that you really need do such things - it seems you're solving some problem with wrong method (see XY-problem description)
You can do it using php eval function.
For that first you have to check for special characters and equation characters.
$val='(100*2)';
echo matheval($val);
function matheval($equation)
{
$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
// fix percentage calcul when percentage value < 10
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
// calc percentage
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
// you could use str_replace on this next line
// if you really, really want to fine-tune this equation
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation == "" )
{
$return = 0;
}
else
{
eval("\$return=" . $equation . ";" );
}
return $return;
}
I not recommended this, but you can use eval to suit your need
eval('$val = (100*2)');
echo intval($val);
Why not just:
$x=intval(100);// <- or an other value from the cleaned user input
$y=intval(2);
$val=$x*$y;
echo $val;
You are not giving a goal.
I can just explain why your code works like it does.
'(100*2)' is a String that cannot be converted to int, since it does contain other chars than numbers. Every String that cannot be converted will result in 0.
echo (int)(100*2) will work, because you use numbers and no strings. No need to convert, either, would work without the cast, just echo (100*2);
Remember PHP use loose typing. You will almost never need to convert types. This scenario is very set up.

Understanding 'parse_str' in PHP

I'm a PHP newbie trying to find a way to use parse_str to parse a number of URLs from a database (note: not from the request, they are already stored in a database, don't ask... so _GET won't work)
So I'm trying this:
$parts = parse_url('http://www.jobrapido.se/?w=teknikinformat%C3%B6r&l=malm%C3%B6&r=auto');
parse_str($parts['query'], $query);
return $query['w'];
Please note that here I am just supplying an example URL, in the real application the URL will be passed in as a parameter from the database. And if I do this it works fine. However, I don't understand how to use this function properly, and how to avoid errors.
First of all, here I used "w" as the index to return, because I could clearly see it was in the query. But how do these things work? Is there a set of specific values I can use to get the entire query string? I mean, if I look further, I can see "l" and "r" here as well...
Sure I could extract those too and concatenate the result, but will these value names be arbitrary, or is there a way to know exactly which ones to extract? Of course there's the "q" value, which I originally thought would be the only one I would need, but apparently not. It's not even in the example URL, although I know it's in lots of others.
So how do I do this? Here's what I want:
Extract all parts of the query string that gives me a readable output of the search string part of the URL (so in the above it would be "teknikinformatör Malmö auto". Note that I would need to translate the URL encoding to Swedish characters, any easy way to do that in PHP?)
Handle errors so that if the above doesn't work for some reason, the method should only return an empty string, thus not breaking the code. Because at this point, if I were to use the above with an actual parameter, $url, passed in instead of the example URL, I would get errors, because many of the URLs do not have the "w" parameter, some may be empty fields in the database, some may be malformed, etc. So how can I handle such errors stably, and just return a value if the parsing works, and return empty string otherwise?
There seems to be a very strange problem that occurs that I cannot see during debugging. I put this test code in just to see what is going on:
function getQuery($url)
{
try
{
$parts = parse_url($url);
parse_str($parts['query'], $query);
if (isset($query['q'])) {
/* return $query['q']; */
return '';
}
} catch (Exception $e) {
return '';
}
}
Now, obviously in the real code I would want something like the commented out part to be returned. However, the puzzling thing is this:
With this code, as far as I see, every path should lead to returning an empty string. But this does not work - it gives me a completely empty grid in the result page. No errors or anything during debugging, and objects look fine when I step through them during debugging.
However, if I remove everything from this method except return ''; then it works fine - of course the field in the grid where the query is supposed to be is empty, but all the other fields have all the information as they should. So this was just a test. But how is it possible that code that should only be able to return an empty string does not work, while the one that only returns an empty string and does nothing else does work? I'm thoroughly confused...
The meaning of the query parameters is entirely up to the application that handles the URL, so there is no "right" parameter - it might be w, q, or searchquery. You can heuristically search for the most common variables (=guess), or return an array of all arguments. It depends on what you're trying to achieve.
parse_str already decodes urlencoding. Note that urlencoding is a way to encode bytes, not characters. It depends on what encoding the application expects. Usually (and in this example query), that should be UTF-8 everywhere, so you should be covered on 1.
Test whether the value exists, and if not, return the empty string, like this:
$heuristicFields = array('q', 'w', 'searchquery');
foreach ($heuristicFields as $hf) {
if (isset($query[$hf])) return $query[$hf];
}
return '';
The function returns null if the input is valid, and runs into errors (i.e., displays warning messages) when the URL is obviously invalid. The try...catch block has no effect.
It turned out the problem was with Swedish characters - if I used utf8_encode() on the value before returning it, it worked fine.

How can I safely use eval in php?

I know some people may just respond "never" as long as there's user input. But suppose I have something like this:
$version = $_REQUEST['version'];
$test = 'return $version > 3;';
$success = eval($test);
This is obviously a simplified case, but is there anything that a user can input as version to get this to do something malicious? If I restrict the type of strings that $test can take on to comparing the value of certain variables to other variables, is there any way anybody can see to exploit that?
Edit
I've tried running the following script on the server and nothing happens:
<?php
$version = "exec('mkdir test') + 4";
$teststr = '$version > 3;';
$result = eval('return ' . $teststr);
var_dump($result);
?>
all I get is bool(false). No new directory is created. If I have a line that actually calls exec('mkdir test') before that, it actually does create the directory. It seems to be working correctly, in that it's just comparing a string converted to a number to another number and finding out the result is false.
Ohhhh boy!
$version = "exec('rm-rf/...') + 4"; // Return 4 so the return value is "true"
// after all, we're gentlemen!
$test = "return $version > 3";
eval($test);
:)
You would have to do at least a filter_var() or is_numeric() on the input value in this case.
By the way, the way you use eval (assigning its result to $success) doesn't work in PHP. You would have to put the assignment into the eval()ed string.
If you do this. Only accept ints.
If you must accept strings, don't.
If you still think you must. Don't!
And lastly, if you still, after that, think you need strings. JUST DON'T!
yes, anything. I would use $version = (int)$_REQUEST['version']; to validate the data.
You need to be more precise with your definitions of "malicious" or "safe". Consider for example
exec("rm -rf /");
echo "enlarge your rolex!";
while(true) echo "*";
all three snippets are "malicious" from the common sense point of view, however technically they are totally different. Protection techniques that may apply to #1, won't work with other two and vice versa.
The way to make this safe would be to ensure that $version is a number BEFORE you try to eval.
Use this code to remove everything except numbers (0-9): preg_replace('/[^0-9]+/', '', $version);

Categories