htmanning has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I need to be able to check if a file exists on the server. The filename is in the database, but may not be on the server. I know how to check the database for the file, but I'm unsure how to verify that the filename is on the server.
$pointer2 = $sth2->fetchrow_hashref; $image = $pointer2->{'image'}; if ($image) { How do I verify it exists? }
Thanks.

Replies are listed 'Best First'.
Re: Check if image file exists
by BrowserUk (Patriarch) on Apr 07, 2012 at 23:42 UTC

    Assuming that $image contains the absolute path to the file:

    $pointer2 = $sth2->fetchrow_hashref; $image = $pointer2->{'image'}; if ($image && -f $image ) { ## it exists } else { ## It doesn't (or the DB query return false) }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      I think I spoke too soon, or I'm doing something wrong. The following doesn't work. It returns all noavatar50.png.
      $picture="/$username/$picture"; if ($picture && -f $picture ) { $thumb30 = "<img src=\"$picture\" width=30 height=30 border=0> +"; } else { $thumb30 = "<img src=\"/images/noavatar50.png\" width=30 h +eight=30 border=0>"; }
      Ideally I'd like to use something like this for the first IF statement, but it doesn't work.
      if (($picture) && ($scope ne "Private") && (-f $picture)) {

        Perl's file-test operators only care about the file's location on your server. If the file's URI is /username/picture.jpg, that's almost certainly not the file's full pathname on your system. That might be something like /var/www/images/username/picture.jpg, or something entirely different. You'll have to prepend $picture with the filesystem location of your picture subdirectory. Also, use a different quoting method to get rid of those backslashed quotes:

        $picture = "/$username/$picture"; my $picture_path = "/var/www/images$picture"; # or whatever if( -f $picture_path ){ $thumb30 = qq| <img src="$picture" /> |; } else { $thumb30 = qq| <img src="/images/noavatar50.png" /> |; }

        Aaron B.
        My Woefully Neglected Blog, where I occasionally mention Perl.

      Perfect. Thanks!
Re: Check if image file exists
by mendeepak (Scribe) on Apr 10, 2012 at 05:57 UTC

    what have you stored in your database a complete sever path like /var/www/project/images/1.jpg or a complete browser path like http://www.yoursite.com/image/1.jpg if its the second one try to get the complete server path and check using if (-e $filename) { print "File Exists!"; }

A reply falls below the community's threshold of quality. You may see it by logging in.