Log in

View Full Version : Resolved converting string to an octal number



james438
11-26-2011, 06:54 PM
I have this editor script that I am attempting to upgrade and I want to add the ability to change the permissions. I can do that easy enough, but when I get the value from $_POST and convert it to an integer I lose the leading 0. 0755 becomes 755. How can I convert the string to an integer and yet preserve the leading zero?


<?php
$str='0755';
$str=(int)$str;
print $str; // produces 755 not 0755.
?>

djr33
11-26-2011, 07:01 PM
Well, integers strictly don't have leading 0s. I think you're supposed to use a string. Or maybe it's an octal value... I can't remember. But an int will always lose that 0 and won't work.

Ah, here's where I read something:
http://www.php.net/manual/en/function.chmod.php
Look through the info there and you'll see why octal numbers are needed. Beyond that, I don't really understand. But I also know that using strings works fine, even if it isn't strictly correct.

james438
11-26-2011, 07:27 PM
I am still looking into this, but I am unable to get strings to work.

$str=0755;works
$str='0755';fails
$str="0755";fails

james438
11-26-2011, 09:26 PM
Got it.


<?php
$str="0755";
echo "$str ";
var_dump(is_int($str));

$str="0755";
$str=intval($str);
echo"<br>$str ";
var_dump(is_int($str));

$str="0755";
$str=intval($str, 8);
echo"<br>$str ";
var_dump(is_int($str));

##chmod("test2.php", intval($str, 8));
?>

produces:

0755 bool(false)
755 bool(true)
493 bool(true)

in php.net it says chmod needs the mode to be in the format of an integer. When passing a value via $_POST this can be a little difficult to do. My guess is that the format is always in a string.

$str="0755"; a string
$str='0755'; a string
$str=0755; a number that is recognized as an octal number. This is not the same as 755. If you echo it you will get 493. I can't use this, because when the number is passed via $_POST I get it in string format. sprint treats the string however you want, but does not convert it. int($str) just converts the string to an integer, but we lose the leading zero. decoct($str) changes dec to oct, but we convert it away from a string in the process.

intval(); will get the integer value of the number as well, but here we run into the same problem where leading zeros are lost. You can, however, specify that you want to preserve the octal format by

intval($str, 8);

base 8 numbering in this case.

I got the hint here (http://www.php.net/manual/en/function.chmod.php#42625).

djr33
11-27-2011, 08:27 PM
Interesting. I knew I'd just used trial and error to get it to work when I needed to, but now I see that it's a little more complicated than strings. Thanks for sharing the info. Glad it's all working now.