PHP: converting String to an integer without removing leading zeros

I have an input field that contains the file mode used for chmod.

If I use this, it is used as a string, so it fails. I convert it to int (intval ()), it removes the initial zero (0777 => 777) and fails again. If I use it like this:

$int = intval($input); $finished = 0 . $int; 

This also does not work, because is_int($finished) is false.

How can i solve this?

+4
source share
5 answers

Leading zeros are a non-existent concept for integers, since they are mathematically insignificant. In decimal notation, the integer 0777 simply and exactly equal to 777 .

But if you are trying to convert "0777" to octal notation into its integer copy ( 511 as decimal) for use with chmod() , you can use octdec($input) . The function takes a string and spits out an integer, doing exactly what it says about the gesture.

Of course, be sure to check first, for example. using regex. You do not want to pass a global or invalid flag to chmod() and potentially publish your sensitive files and folders.

+5
source

You use the input field to get $input . This means that the value is a string.

You are looking for an octal number inside this value. intval does not treat strings as octal numbers.

chmod expects the $mode parameter to be integer.

To convert a string containing an octal number, you can use the octdec function:

 $int = octdec($value); # '0777' -> 511 

That way, you can verify that the input is correct and check whether it also matches the octal number, for example, by converting it again with decoct and testing if it leads to the same:

 $valid = "0".decoct($int) === $value; 
+2
source

Try checking the input with preg_match (). see below code.

 if(preg_match("/[^0-9.]/", $input)) { return false; } else { -- Some Code Here -- } 

Thanks.

+1
source

There is nothing to decide, an integer type cannot start with 0 if its value is 0. 0777 is 777 by value, there is usually no problem setting the resolution as 777, the system will know to treat it as 0777.

If you SHOULD pass an initial zero, it should be like a string (for example, '0'.$finished )

Shay.

+1
source

When you use the function 0. $ INT; php understands that the operation adds two lines. The result of $ finished will be a string. try using the number_format function to solve.

0
source

Source: https://habr.com/ru/post/1380154/


All Articles