简体   繁体   中英

PHP: Detecting file extension from: filename.jpg

Yes as the title says:

How can i detect an file extension? $_POST['fname']; is where i have the filename stored eg asddsa.jpg

So how can i check if .jpg then ... if .png then ... ?

    $src = "images/status/photo/".$_POST['fname'];
    $parts=pathinfo($src);
if($parts['extension'] == "jpg"){
    $img_r = imagecreatefromjpeg($src);
}elseif($parts['extension'] == "png"){
    $img_r = imagecreatefrompng($src);
}elseif($parts['extension'] == "gif"){
    $img_r = imagecreatefromgif($src);
}

tried this too without any success:

    $ext= pathinfo($src, PATHINFO_EXTENSION);
if($ext == "jpg"){
    $img_r = imagecreatefromjpeg($src);
}elseif($ext == "png"){
    $img_r = imagecreatefrompng($src);
}elseif($ext == "gif"){
    $img_r = imagecreatefromgif($src);
}

The proper way to do this would be to use pathinfo on the file. For example...

$parts=pathinfo('somefile.jpg');
echo $parts['extension']; //Returns "jpg"

Now, you're simply looking at a string in a variable, so the way to handle this would be something like this ...

$parts=explode(".", $_POST['fname']);
echo $parts[count($parts)-1];

Finally, you should not be detecting file type by extension. This is bad. Instead, you should be using the content-type (commonly referred to as MIME type). You can find this in $_FILES['userfile']['type'] for uploaded files. ( documentation )

Once you have your type, you can do a simple switch statement .

Also, beware of folks uploading content that isn't what it says it is. Someone can send files to you with a specific content type, but it may be something such as executable code instead! The only way to be sure is to check the files with your own code server-side. Never trust user input.

You can do something like this:

$aPieces = explode( '.', $_POST[ 'fname' ] ); // A file name can have more than 1 .something

switch( strtolower( $aPieces[ count( $aPieces) - 1 ] ) ) // We take the LAST piece in our array
{
   case 'jpg':

   break;
   case 'png':

   break;
}

The solution really depends on what you're trying to do, however the simple approach would be something like:

if ( strtolower(substr($_POST['fname'],-3)) == 'jpg' )

You can also switch() on the string instead of using if/else depending on how many comparisons you will be making.

Edit: if you are going to be specifically dealing with images, you're best off using getimagesize

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