Home > Blockchain >  PHP validating XML inputs as ints
PHP validating XML inputs as ints

Time:02-24

When running this code it takes an XML input and parses the key values into variables to make a simple arithmetic calculation. I attempt manually validate the user input to ensure tags number1 and number2 are integers;

When echoing the variables they appear as integers but still meet the condition as if they aren't. Please let me know if you can see any problems.

<?php
    $XML = “<?xml version='1.0' encoding='UTF-8'?>.           
<arithmetic> 
<operation>add</operation>
<number1>5</number1>
<number2>3</number2>
</arithmetic>”;
    $equation = simplexml_load_string($XML); //loads xml into variable
    $operation = $equation->operation; // loads operation into variable
    $number1 = $equation->number1; // loads number1 into variable
    $number2 = $equation->number2; //loads number2 into variable

    // If the values entered are not numbers return error message
    if(is_numeric($number1) != 1){  
        $number1 = "";
        echo " Incorrect number 1 entered  ";
    }
    if(is_numeric($number2) != 1){
        $number2 = "";
        echo " Incorrect number 2 entered   ";
    }
.....

CodePudding user response:

If you do var_dump on the number1, you will see that it is not a string, but an object of type SimpleXMLElement.

object(SimpleXMLElement)[3]
  public 0 => string '1' (length=1)

So simply cast the variables in order to convert them to string:

$operation = (string) $equation->operation; // loads operation into variable
$number1 =(string) $equation->number1; // loads number1 into variable
$number2 = (string) $equation->number2; //loads number2 into variable

Update: This will call ::__toString() under the hood. check the docs.

CodePudding user response:

PHP's is_numeric() essentially tests whether the number or string is formatted like a number, e.g. "123" or "123.45" (strings) or 123 or 123.45 (integers and floats respectively).

There's is_int() but that checks whether the type of the variable is integer. This won't help you because you're starting with a string.

Building on @pouria's answer: since you're starting with an object, you'll need to first convert it to a string with

$number1 =(string) $equation->number1;

That will get you a string, but to test whether it is "integer-like" (i.e. consists of only digits) you can do this:

// Test whether $number1 consists of at least one digit:
if ( preg_match( '/^\d $/', $number1 ) ) {
  // $number1 is an integer!
} else {
  // $number1 is NOT an integer (or is empty)!
}

If you want to allow an optional leading sign ( /-) in your integers, change the regexp to:

'/^[ -]?\d $/'

Once you've determined whether $number is integer-like, you may need to convert it to an actual integer (depending on how you intend to use it):

$number1 = (int) $number1;
  • Related