Created
February 5, 2025 03:14
-
-
Save markallenpark/8c6697b80ed474abfb4d86e8e3757da0 to your computer and use it in GitHub Desktop.
Simple php script to teach myself bitwise operations - also handy utility for calculating Unix/Linux file permissions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$input_valid = false; | |
while ( ! $input_valid ) { | |
$input = readline('Input octal permission string: '); | |
if (! preg_match('/[0-7]/', $input)) | |
{ | |
echo "Invalid input!\n"; | |
continue; | |
} | |
if (mb_strlen($input) > 4) | |
{ | |
echo "Invalid input!\n"; | |
continue; | |
} | |
$input_valid = true; | |
} | |
$input = octdec($input); | |
$flags = [ | |
"special" => [ | |
's' => 0o4000, | |
'g' => 0o2000, | |
't' => 0o1000, | |
], | |
"owner" => [ | |
'r' => 0o400, | |
'w' => 0o200, | |
'x' => 0o100, | |
], | |
"group" => [ | |
'r' => 0o40, | |
'w' => 0o20, | |
'x' => 0o10, | |
], | |
"other" => [ | |
'r' => 0o4, | |
'w' => 0o2, | |
'x' => 0o1 | |
] | |
]; | |
$permissions = ''; | |
$special = $flags['special']; | |
$permissions .= "Special | Owner | Group | Other\n"; | |
$permissions .= " "; | |
$permissions .= ($input & $special['s']) ? 's' : '-'; // SUID | |
$permissions .= ($input & $special['g']) ? 'g' : '-'; // SGID | |
$permissions .= ($input & $special['t']) ? 't' : '-'; // Sticky | |
$permissions .= " | "; | |
$owner = $flags['owner']; | |
$permissions .= ($input & $owner['r']) ? 'r' : '-'; | |
$permissions .= ($input & $owner['w']) ? 'w' : '-'; | |
$permissions .= ($input & $owner['x']) ? 'x' : '-'; | |
$permissions .= " | "; | |
$group = $flags['group']; | |
$permissions .= ($input & $group['r']) ? 'r' : '-'; | |
$permissions .= ($input & $group['w']) ? 'w' : '-'; | |
$permissions .= ($input & $group['x']) ? 'x' : '-'; | |
$permissions .= " | "; | |
$other = $flags['other']; | |
$permissions .= ($input & $other['r']) ? 'r' : '-'; | |
$permissions .= ($input & $other['w']) ? 'w' : '-'; | |
$permissions .= ($input & $other['x']) ? 'x' : '-'; | |
echo $permissions . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would note there are much better ways to do this, this was just for practice and learning.