filetype

  • PHP’s filetype performs a stat on a file and returns a string representing its type.

    PHP

    $type = filetype('/path/to/foobar');
    var_export($type);
    //=> "file"

    The File.ftype class method in Ruby performs the same task.

    Ruby

    type = File.ftype('/path/to/foobar')
    p type
    #=> "file"

    This table shows the strings returned by each version.

    PHP Ruby
    link link
    fifo fifo
    char characterSpecial
    dir directory
    block blockSpecial
    file file
    socket No equivalent
    unknown unknown

    Checking for a Specific File Type

    Perhaps the most common usage of filetype is to check if a path is a specific type, such as this example which checks if the path is a dir.

    PHP

    if (filetype('/path/to/foobar') == 'dir') {
      // ...
    }

    You can do this with the string returned by File.ftype as well but File also provides convenience methods like file? and directory? that make code more readable.

    Ruby

    if File.directory?('/path/to/foobar')
      # ...
    end

    Working with File::Stat Instances

    The File::Stat instance returned by Ruby’s File.stat also supports the methods shown above and more.

    Ruby

    stat = File.stat('/path/to/foobar')
    p stat.ftype
     
    #=> "file"

    Ruby

    stat = File.stat('/path/to/foobar')
    if stat.directory?('/path/to/foobar')
      # ...
    end

    see also

filesize fopen

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.