开发者

PHP: Detecting file extension from: filename.jpg

开发者 https://www.devze.com 2023-01-23 09:58 出处:网络
Yes as the title says: How can i detect an file extension? $_POST[\'fname\']; is where i have the filename stored e.g asddsa.jpg

Yes as the title says:

How can i detect an file extension? $_POST['fname']; is where i have the filename stored e.g 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 =开发者_Go百科= "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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号