Wednesday, November 28, 2018

PHP File Permissions

PHP File Permissions

Summary: in this tutorial, you will learn how to deal with PHP file permissions including checking and changing file permissions.
File permissions specify what you can do with a particular file in the system e.g., reading, writing or executing the file. Notice that PHP automatically grants appropriate permissions behind the scenes. For example, if you creates a new file for writing, PHP automatically grants read and write permissions to you.
In addition, PHP also provides some useful functions for checking and changing the file permissions.

PHP checking file permissions

PHP gives you three handy functions that allow you to check file permissions:
  • is_readable() returns true if you are allowed to read the file, otherwise returns false.
  • is_writable() returns true if you are allowed to write the file, otherwise returns false.
  • is_executable() returns true if you are allowed to execute the file, otherwise returns false.
Let’s take a look at the following example:
Besides those functions, PHP also provides the fileperms() function that returns an integer, which represents the permissions that are set on a particular file.

PHP changing file permissions

To change the file permissions, or mode, you use chmod() function. First, you need to pass the name of the file that you want to set permission. Second, you need to specify the desired permission. The chmod() function returns true if the permission was set successfully otherwise it returns false.
A file permission is represented by an octal number that contains three digits:
  • The first digit specifies what the owner of the file can do with file.
  • The second digit specifies what the owner group of the file can do with the file.
  • The third digit specifies what everyone can do with the file.
The following table illustrates the value of each digit that represents the access permission for particular users ( user, user group or everyone) :
ValuePermission
0cannot read, write or execute
1can only execute
2can only write
3can write and execute
4can only read
5can read and execute
6can read and write
7can read, write and execute
For example, to set a permission that only creator or owner can read and write a file, everyone else only can read the file, we use the following code:
Notice that we put 0 before 644 to ask PHP to interpret it as an octal number.

No comments:

Post a Comment

form validation

function formsubmit ( ) { var empname = document .getElementById ( 'emp_name' ). value ; var email = document .getElem...