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";
?>

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.

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.

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.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.