简体   繁体   中英

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];

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.

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, eg:

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;
 }

尝试这个,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM