Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Conversion String to integer without deleting leading zeroes

Tags:

php

int

I've got an input field which contains the file mode used for chmod.

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

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

This also fails because is_int($finished) is false.

How can I solve this?

like image 311
Florian Müller Avatar asked Jan 18 '23 08:01

Florian Müller


1 Answers

Leading zeroes are a nonexistent concept for integers, because they are mathematically insignificant. In decimal notation, the integer 0777 is simply and exactly equal to 777.

But if you're trying to convert "0777" in octal notation to its integer counterpart (511 as a 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 on the tin.

Of course, be sure you perform validation first, e.g. by using a regex. You don't want to hand a global or invalid flag to chmod() and potentially expose your sensitive files and folders to the public.

like image 82
BoltClock Avatar answered Apr 28 '23 00:04

BoltClock