2

I am making a CLI utility using PHP that will run on Windows and Linux, and I need to check whether a specified file is a device file.

I've had a look at How to guarantee a specified file is a device on BSD/Linux from PHP? but none of the approaches worked on multiple OSes.

How to approach this in a functional way?


On Linux stat() works on most files, but I don't know how to differentiate device vs regular files.

Running stat("con") on Windows returns an error whereas stat("nul") does not.

oxou
  • 148
  • 1
  • 6
  • Hmmmm, `CON` and `NUL` are provided by the shell, yeah? A solution might be specific to what shell you're running on under Windows... might have to just be hardcoded. – Brad Jun 22 '23 at 05:01

1 Answers1

0

I don't know if this is portable to Windows, but on Unix the file type is in octal digits 5-6 (from the right) of the mode element returned by stat().

$stat = stat("filename");
$type = $stat[2] & 0770000;
$is_device = $type == 0060000 || $type == 0020000;

0060000 is a block device, 0020000 is a character device.

See the above documentation for the list of all file type values.

Barmar
  • 741,623
  • 53
  • 500
  • 612