Combining These Two Variables - php

I'm trying to combine these two:
$test1 = (isset($_GET["var1"]) && (isset($_GET["var2"]);
$test2 = test = !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE );
This is what I tried thats giving me an unexpected ; parse error parse error:
$test1 = (isset($_GET["var1"]) &&
!(strpos($_GET['var1'], '{') !== FALSE ||
strpos($_GET['var1'], '}') !== FALSE ) ||
(isset($_GET["var2"]) &&
!(strpos($_GET['var2'], '{') !== FALSE ||
strpos($_GET['var2'], '}') !== FALSE );
EDIT
what $test1 does is checks to see if var1 and var2 are in the url
what $test2 does is checks to see if var1= or var2= has { or } in the string. I'm just trying to put this all into 1 variable

Bad parenthesis on line 1, and I assume you want that to be '$test', not 'test' on line 2:
<?php
$test1 = isset($_GET['var1']) && isset($_GET['var2']);
$test2 = $test = !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE );

This code works:
$_GET['var1'] = "vvv";
$_GET['var2'] = "ddd";
$test1 = (isset($_GET["var1"]) && !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE ) ||
(isset($_GET["var2"]) && !(strpos($_GET['var2'], '{') !== FALSE || strpos($_GET['var2'], '}') !== FALSE )));
print $test1;
In short this is a mess. Don't do that you'll never recognize what it does after 6 month or so.

This is a little verbose, but may change the way you're thinking about this.
$test1 will have a truthy value if both vars are set. test2 will have a truthy value if the either { or } exists in the string.
function testBrackets($string)
{
$firstBracket = strpos($string, '{');
$secondBracket = strpos($string, '}');
if ($firstBracket == false and $secondBracket == false)
{
return false;
}
return true;
}
if (isset($_GET['var1']) and isset($_GET['var2']))
{
$test1 = true;
}
$test2 = 0;
if (isset($_GET['var1']))
{
$test2 = $test2 + testBrackets($_GET['var1']);
}
if (isset($_GET['var2']))
{
$test2 = $test2 + testBrackets($_GET['var2']);
}

Related

PHP Zero integer is being evaluated as false

As the title says, PHP seems to be evaluating the integer value 0 as false.
Take for example this snippet:
http://sandbox.onlinephpfunctions.com/code/13d885fb68359a3154999c2ef85db7c913c49bc5
<?php
if($exists = checkDup()){
echo $exits;
}
else{
echo "error!";
}
function checkDup ($foo = 'blah', $bar = 'blah'){
if ($foo == $bar) return (int) 0;
return false;
}
As you can see, despite casting the reply as an int PHP parsing the return as false which in incorrect.
PHP is evaluating a lot to false ;)
For example null, '', 0
You have to include a type check as well, you can do so by using === or !==
$exists = checkDup();
if($exists !== false){
echo $exits;
}
else{
echo "error!";
}
function checkDup ($foo = 'blah', $bar = 'blah'){
if ($foo == $bar) return 0;
return false;
}
You should use if($exists = checkDup() !== false)
0 == false; //true
0 === false; //false
When you don't specify the a boolean expression in the if, it will execute the == operator

If a $var1 equals a string then set $var2 equal to another string

Basically if $var1 = 'Refi' then I want $var2 = 'Refinance'. If $var = 'Purch' or 'Purchase' then I need $var2 = 'Purchase'.
$var2 = '';
if (!(strcasecmp($var1, 'Refi') === false)) {
$var2 = 'Refinance';
}
if (!(strcasecmp($var1, 'Purch') === false) || !(strcasecmp($var1, 'Purchase') === false)) {
$var2 = 'Purchase';
}
The output I am getting is just defaulting to 'Purchase'. I also need the strings to be case insensitive. I don't know what is going on with it, the logic seems correct in my help.
strcasecmp does not return a bool. It returns an int.
$var2 = '';
if ((strcasecmp($var1, 'Refi') == 0)) {
$var2 = 'Refinance';
}
if ((strcasecmp($var1, 'Purch') == 0) || (strcasecmp($var1, 'Purchase') == 0)) {
$var2 = 'Purchase';
}
Check out documentation for details. http://php.net/manual/en/function.strcasecmp.php

Function returning boolean only returns false

I've a simple function that apprently puts me up with a lot of trouble. The function is:
function valid_mail($email) {
$atpointers = strstr($email, "#");
$spacepointers = count(explode(" ", $email));
$dotpointers = strstr($email, ".");
$ltpointers = strstr($email, "<");
$gtpointers = strstr($email, ">");
$illegalpts = $ltpointers + $gtpointers;
if($atpointers >= 2 || $dotpointers == 0 || strlen($email) <= 6 || $illegalpts >= 1) { return false; } else { return true; }
}
And calling it in the context:
if(valid_mail($email) === false) { // Code } else { // Code }
The problem is apparently it only returns false. Any ideas for why this happens ?
strstr returns a substr of the string being checked, not a length. Use strpos instead.

Needle is in haystack but barn door is jammed shut!

The test below returns false ($pos = 0) when $haystack = "my keyword" and $needle = "my keyword", presumably because my stripos test returns 0 since there is no empty space in the barn.
What do I need to change in the comparison to return true in this case?
function my_test($post){
if($post->post_title == "") return false;
$haystack = my_esc2($post->post_title);
$needle = trim(my_getKeyword($post));
$pos = stripos($haystack, $needle);
if ($pos !== false) return true;
//returns 0 when $needle and $haystack are the same exact phrase. but should return 1
}
function my_getKeyword($post)
{
$myKeyword = get_post_meta($post->ID, '_my_keyword', true);
if($myKeyword == "") $myKeyword = $post->post_title;
$myKeyword = my_esc($myKeyword);
return " ".$myKeyword;
}
function my_esc($str, $quotation='"') {
if ($quotation != '"' && $quotation != "'") return false;
return str_replace($quotation, $quotation.$quotation, $str);
}
function my_esc2($str, $quotation='"') {
if ($quotation != '"' && $quotation != "'") return false;
return str_replace($quotation, '', $str);
}
If both strings are the same, stripos is supposed to return 0 as 0 is the position in the string where the match if found.
However, you are using the !== operator, so that test should return true anyway (by the way, you can just use return ($pos !== false)).
Are you sure you are getting to that statement, can you echo both $haystack and $needle right before the return statement?
It seems to me that haystack and needle are not the same or needle is not found or ($post->post_title == "")...

Check to see if a string is serialized?

What's the best way to determine whether or not a string is the result of the serialize() function?
https://www.php.net/manual/en/function.serialize
I'd say, try to unserialize it ;-)
Quoting the manual :
In case the passed string is not
unserializeable, FALSE is returned and
E_NOTICE is issued.
So, you have to check if the return value is false or not (with === or !==, to be sure not to have any problem with 0 or null or anything that equals to false, I'd say).
Just beware the notice : you might want/need to use the # operator.
For instance :
$str = 'hjkl';
$data = #unserialize($str);
if ($data !== false) {
echo "ok";
} else {
echo "not ok";
}
Will get you :
not ok
EDIT : Oh, and like #Peter said (thanks to him!), you might run into trouble if you are trying to unserialize the representation of a boolean false :-(
So, checking that your serialized string is not equal to "b:0;" might be helpful too ; something like this should do the trick, I suppose :
$data = #unserialize($str);
if ($str === 'b:0;' || $data !== false) {
echo "ok";
} else {
echo "not ok";
}
testing that special case before trying to unserialize would be an optimization -- but probably not that usefull, if you don't often have a false serialized value.
From WordPress core functions:
<?php
function is_serialized( $data, $strict = true ) {
// If it isn't a string, it isn't serialized.
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' === $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace ) {
return false;
}
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 ) {
return false;
}
if ( false !== $brace && $brace < 4 ) {
return false;
}
}
$token = $data[0];
switch ( $token ) {
case 's':
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// Or else fall through.
case 'a':
case 'O':
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b':
case 'i':
case 'd':
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
}
return false;
}
Optimizing Pascal MARTIN's response
/**
* Check if a string is serialized
* #param string $string
*/
public static function is_serial($string) {
return (#unserialize($string) !== false);
}
If the $string is a serialized false value, ie $string = 'b:0;'
SoN9ne's function returns false, it's wrong
so the function would be
/**
* Check if a string is serialized
*
* #param string $string
*
* #return bool
*/
function is_serialized_string($string)
{
return ($string == 'b:0;' || #unserialize($string) !== false);
}
Despite Pascal MARTIN's excellent answer, I was curious if you could approach this another way, so I did this just as a mental exercise
<?php
ini_set( 'display_errors', 1 );
ini_set( 'track_errors', 1 );
error_reporting( E_ALL );
$valueToUnserialize = serialize( false );
//$valueToUnserialize = "a"; # uncomment this for another test
$unserialized = #unserialize( $valueToUnserialize );
if ( FALSE === $unserialized && isset( $php_errormsg ) && strpos( $php_errormsg, 'unserialize' ) !== FALSE )
{
echo 'Value could not be unserialized<br>';
echo $valueToUnserialize;
} else {
echo 'Value was unserialized!<br>';
var_dump( $unserialized );
}
And it actually works. The only caveat is that it will likely break if you have a registered error handler because of how $php_errormsg works.
$data = #unserialize($str);
if($data !== false || $str === 'b:0;')
echo 'ok';
else
echo "not ok";
Correctly handles the case of serialize(false). :)
build in to a function
function isSerialized($value)
{
return preg_match('^([adObis]:|N;)^', $value);
}
There is WordPress solution: (detail is here)
function is_serialized($data, $strict = true)
{
// if it isn't a string, it isn't serialized.
if (!is_string($data)) {
return false;
}
$data = trim($data);
if ('N;' == $data) {
return true;
}
if (strlen($data) < 4) {
return false;
}
if (':' !== $data[1]) {
return false;
}
if ($strict) {
$lastc = substr($data, -1);
if (';' !== $lastc && '}' !== $lastc) {
return false;
}
} else {
$semicolon = strpos($data, ';');
$brace = strpos($data, '}');
// Either ; or } must exist.
if (false === $semicolon && false === $brace)
return false;
// But neither must be in the first X characters.
if (false !== $semicolon && $semicolon < 3)
return false;
if (false !== $brace && $brace < 4)
return false;
}
$token = $data[0];
switch ($token) {
case 's' :
if ($strict) {
if ('"' !== substr($data, -2, 1)) {
return false;
}
} elseif (false === strpos($data, '"')) {
return false;
}
// or else fall through
case 'a' :
case 'O' :
return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
case 'b' :
case 'i' :
case 'd' :
$end = $strict ? '$' : '';
return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
}
return false;
}
/**
* some people will look down on this little puppy
*/
function isSerialized($s){
if(
stristr($s, '{' ) != false &&
stristr($s, '}' ) != false &&
stristr($s, ';' ) != false &&
stristr($s, ':' ) != false
){
return true;
}else{
return false;
}
}
This works fine for me
<?php
function is_serialized($data){
return (is_string($data) && preg_match("#^((N;)|((a|O|s):[0-9]+:.*[;}])|((b|i|d):[0-9.E-]+;))$#um", $data));
}
?>
I would just try to unserialize it. This is how i would solve it
public static function is_serialized($string)
{
try {
unserialize($string);
} catch (\Exception $e) {
return false;
}
return true;
}
Or more like a helper function
function is_serialized($string) {
try {
unserialize($string);
} catch (\Exception $e) {
return false;
}
return true;
}
The mentionned WordPress function does not really detect arrays (a:1:{42} is considered to be serialized) and falsely returns true on escaped strings like a:1:{s:3:\"foo\";s:3:\"bar\";} (although unserialize does not work)
If you use the #unserialize way on the other side WordPress for example adds an ugly margin at the top of the backend when using define('WP_DEBUG', true);
A working solution that solves both problems and circumvents the stfu-operator is:
function __is_serialized($var)
{
if (!is_string($var) || $var == '') {
return false;
}
set_error_handler(function ($errno, $errstr) {});
$unserialized = unserialize($var);
restore_error_handler();
if ($var !== 'b:0;' && $unserialized === false) {
return false;
}
return true;
}
see the wordpress function is_serialized
function is_serialized( $data, $strict = true ) {
// If it isn't a string, it isn't serialized.
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' === $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace ) {
return false;
}
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 ) {
return false;
}
if ( false !== $brace && $brace < 4 ) {
return false;
}
}
$token = $data[0];
switch ( $token ) {
case 's':
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// Or else fall through.
case 'a':
case 'O':
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b':
case 'i':
case 'd':
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
}
return false;
}

Categories