user1166981
user1166981

Reputation: 1746

PHP - Grabbing the file extension of a path

Does this grab the file extension of the path? It forms part of a file upload script which goes on to check that $end is "jpg" and not something else. Could that be bypassed given what I have below?

$temp = strlen($path);
$end = $path[$temp-3] . $path[$temp-2] . $path[$temp-1];

Upvotes: 0

Views: 231

Answers (3)

Jelmer
Jelmer

Reputation: 2693

Have a look at: http://php.net/manual/en/function.pathinfo.php

mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";    # returns: /www/htdocs/inc
echo $path_parts['basename'], "\n";   # returns: lib.inc.php
echo $path_parts['extension'], "\n";  # returns: php
echo $path_parts['filename'], "\n";   # returns: lib.inc  | since PHP 5.2.0
?>

Or you could set the flag to get only the extension, like so:

$extension = pathinfo('/www/htdocs/inc/lib.inc.php', PATHINFO_EXTENSION);
echo $extension; # prints `php` to the screen.

Upvotes: 6

Phil Rykoff
Phil Rykoff

Reputation: 12087

if you want to make sure that a valid image was uploaded, don't rely on the file ending, which can be tampered with. You may use the PHP image functions to make sure, that a file really is an image, e.g.:

function is_image($path) {
    $a = getimagesize($path);
    $image_type = $a[2];

    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP)))
    {
         return true;
    }
    return false;
 }

Upvotes: 2

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

Try this,

$ext = pathinfo('abc.jpeg' ,PATHINFO_EXTENSION);

Upvotes: 1

Related Questions