Jump to content

Checking for proper file extensions, if present, return true...


cgm225

Recommended Posts

<?php
  header('Content-type: text/plain');
  $filename='some.jPeG';
  echo preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)."\n";
  $filename='some.gif';
  echo preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)."\n";
  $filename='some.PNG';
  echo preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)."\n";
  $filename='some.php.gif';
  echo preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)."\n";
  $filename='some.php';
  echo preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)."\n";
?>

Link to comment
Share on other sites

I want to check a file name, and if it has the file extension jpg, jpeg, JPG, JPEG, gif, GIF, png, PNG (and all other variations), then I want the code to return TRUE.

 

Be very careful what you wish for. If you really want to be sure the file is an image, then run the getimagesize() function on it.

Link to comment
Share on other sites

In the book "object oriented programming", the author has a function that checks that all files in a directory are images:

 

function checkAllImages(){
	$bln=true;
	$extension='';
	$types= array('jpg', 'jpeg', 'gif', 'png');
	foreach ($this->filearray as $value){
		$extension = substr($value,(strpos($value, ".")+1));
		$extension = strtolower($extension);
		if(!in_array($extension, $types)){
			$bln = false;
			break;
		}
	}
	return $bln;

 

$filearray is an array of all of the files in the directory.

Link to comment
Share on other sites

if u use strpos, it will find the first occurance

 

use strrpos instead which finds the last occurance.

 

in the example i use

preg_match('/^.+\.(jpg|jpeg|gif|png)$/i',$filename)

smallest way of accomplishing of what is asked, without extra support functions

 

however as Andy states, an extension does not deem it a valid image.

try using the image information routines to validate a valid image.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.