Is there a way to switch “Hidden” or “Read Only” to a Windows file using PHP?

UPDATED

As the title says, is there a way to toggle the Hidden or Read-Only switch on Windows using PHP?

I would like to do this without opening the exec() shell if possible.

+3
source share
5 answers

A file cannot be hidden; it is always in the file system. There is a * NIX convention that files starting with . are not displayed by default for certain operations (for example, the ls ), but only if you do not look heavy enough. The same goes for Windows, but Windows processes it with meta-attributes of files.

What you can / should do is use file permissions to make the folder / file inaccessible to those who do not have access to it. Use chmod , chown and chgrp to do this with PHP. You may need to learn a little about the correct file system permissions.

+3
source

To make a file “hidden” in Windows, you can use

 attrib +h yourfile.ext 

To make a read-only file on Windows, you can use

 attrib +r yourfile.ext 

To use these commands from PHP, you simply execute them using system or exec.

Also see: Attrib

+3
source

On Linux / Unix, you can make a file hidden by putting a period ( . ) At the beginning of your name and using the chmod function to make the file read-only. Not sure about Windows.

+1
source

Although there are some reports on the Internet that PHP chmod can actually set Windows attribute flags (at least read-only), I could not reproduce this at all.
So bypassing the attrib is the way to go.

READ-ONLY for Windows and * nix

Here is some code to install a read-only file that will work on Windows and * nix:

 // set file READ-ONLY (Windows & *nix) $file = 'path/to/file.ext'; if(isset($_SERVER['WINDIR'])) { // Host OS is Windows $file = str_replace('/', '\\', $file); unset($res); exec('attrib +R ' . escapeshellarg($file), $res); $res = $res[0]; }else{ // Host OS is *nix $res = chmod($file, 0444); } //$res contains result string of operation 

Tips:
Replacing '/' with '\' is important because the shell command ( attrib ) is not slash-tolerant like PHP does.
$ res is not installed on the Windows part because exec () adds any existing value.

HIDDEN on Windows

If you want to hide the file, this will probably be a task only for Windows:

 // set file HIDDEN (Windows only) $file = 'path/to/file.ext'; $file = str_replace('/', '\\', $file); unset($res); exec('attrib +H ' . escapeshellarg($file), $res); $res = $res[0]; //$res contains result string of operation 
+1
source

For file permissions, try the chmod function:

 <?php chmod("/somedir/somefile", 0755); // octal; correct value of mode ?> 

More details here: http://php.net/manual/en/function.chmod.php

0
source

Source: https://habr.com/ru/post/1338892/


All Articles