Showing entries with tag "file".

Found 3 entries

Perl: Get file permissions

If you need to see if a file is world readable you'll need to be able to break out file permissions.

my @p     = get_file_permissions("/tmp/foo.txt");
my $other = $p[2];

# 4 = readable, 2 = writeable, 1 = executable
if ($other & 4) { print "File is world readable\n"; }
if ($other & 2) { print "File is world writeable\n"; }
if ($other & 1) { print "File is world executable\n"; }
sub get_file_permissions {
    my $file = shift();

    my @x    = stat($file);
    my $mode = $x[2];

    my $user  = ($mode & 0700) >> 6;
    my $group = ($mode & 0070) >> 3;
    my $other = ($mode & 0007);

    my @ret = ($user, $group, $other);

    return @ret;
}
Leave A Reply

Perl: Read a text file backwards by lines

I needed to read through a log file looking for certain entries backwards (newest entries first). Perl has a File::ReadBackwards module that does exactly this:

use File::ReadBackwards;

my $file = "/var/log/message";
my $fh   = File::ReadBackwards->new($file) or die "can't read $file";

while (my $line = $fh->readline()) {
    print $line;
}
Leave A Reply

PHP: Serve file for download

If you want to a simple way to serve a file for download in PHP you can use this function:

function serve_file($filepath) {
    $filename = basename($filepath);

    if (headers_sent()) {
        die("Cannot output file because output already started");
    }

    $mime_type = mime_content_type($filepath);
    header("Content-type: $mime_type");
    header("Content-Disposition: attachment; filename=\"$filename\"");

    readfile($filepath);

    exit(0);
}
Leave A Reply