04/10/2018, 17:50

Kiểm tra quyền truy cập file (file permission) trong PHP

PHP cung cấp cho chúng ta một function là fileperms() được dùng để lấy thông tin quyền truy cập file (file permission). Và dựa vào function này, mình xin chia sẻ cho các bạn một đoạn code dùng để kiểm tra thông tin truy cập file hoặc folder trên web server. <?php function ...

file-permissions-in-php

PHP cung cấp cho chúng ta một function là fileperms() được dùng để lấy thông tin quyền truy cập file (file permission). Và dựa vào function này, mình xin chia sẻ cho các bạn một đoạn code dùng để kiểm tra thông tin truy cập file hoặc folder trên web server.

<?php

function file_permission($filename){
$perms = fileperms($filename);

if (($perms & 0xC000) == 0xC000) { $info = 's'; }
elseif (($perms & 0xA000) == 0xA000) { $info = 'l'; }
elseif (($perms & 0x8000) == 0x8000) { $info = '-'; }
elseif (($perms & 0x6000) == 0x6000) { $info = 'b'; }
elseif (($perms & 0x4000) == 0x4000) { $info = 'd'; }
elseif (($perms & 0x2000) == 0x2000) { $info = 'c'; }
elseif (($perms & 0x1000) == 0x1000) { $info = 'p'; }
else { $info = 'u'; }

$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));

$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));

$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));

return $info;
}

?>

Và bây giờ , để kiểm tra thông tin truy cập của file nào, thì các bạn dùng như sau :

<?php
  $fileName = "myFile.php";
  echo file_permission($fileName);
?>

Bài viết tuy ngắn ngủi nhưng mình cũng hy vọng với đoạn code bên trên, các bạn có thể áp dụng vào những dự án web của riêng mình sau này.

Tags: code Snipppets coding file permission php code

Chuyên Mục: PHP

Bài viết được đăng bởi webmaster

0