Scripts

[Class] File Uploader

Dit is mijn eerste script hier. Ik hoop dat veel mensen hem kunnen gebruiken. Waarom een file-upload classe? De laatste tijd moest ik veel uploadformulieren in elkaar zetten, en het was altijd zo'n gepruts om het weer allemaal voor elkaar te krijgen dat ik besloot een classe hiervoor te schrijven. We hebben hier toch al een classe hiervoor? Hier is inderdaad een oudere upload classe te vinden. Alleen die classe is voor php 4 gemaakt, mist bijvoorbeeld de mime check en gebruikt nog echo's in de functies. Daarom ben ik een nieuwe gaan maken Ik heb een bug Dat kan natuurlijk, meld hem ff bij de reacties dan kijk ik er ff naar, de classe is nog in de test fase. Er zit geen documentatie bij Dat klopt, maar voel je vrij om er 1 te schrijven ;-) Over de classe: Met deze classe kan je alle bestanden die je wilt uploaden, je kan instellen hoe groot de files mogen zijn, en in het geval van een plaatje ook hoe breed en hoe hoog. De classe heeft de mogelijkheid om op extension en op mime-type te controleren. Dit geldt echter alleen voor plaatjes. Voor andere bestanden (.doc, .txt, .enz) kan je alleen de extension check gebruiken. Op- of aanmerkingen? Die zou ik graag horen, dan weet ik wat er voor de volgende versie verbeterd kan worden. Uitleg: Simpele class, de functies spreken wel voor zich, zie ook voorbeeld onderaan. Op het moment dat de class voor iets anders dan voor afbeeldingen wordt gebruikt, werkt mime-type controllen niet meer. Dit komt omdat ik nog geen functie heb gevonden om een mimetype van zo'n bestand te achter halen. Dit is dus niet veilig! Hoe te gebruiken: Gooi de class in een map (bv class/cUpload.php), die kan je vervolgens vanuit een ander bestand includen, je stelt de functies in en het werkt. NB: Krijg je een error met iets als Permission denied, dan moet je de map nog Chmod'den naar 0777. Dit is met een ftp programma een fluitje van een cent.

class-file-uploader
De class
[code]<?php
//*******************************************/
// Auteur: D-lightweb.nl
// Datum: 09-06-2008
// 
//
// ChangeLog:
//  +
//******************************************/
class UploadFile
{
	############################### Properties (Alfabetisch)
		
	protected $aErrors = array();
	protected $aExt = array();
	protected $aMimeTypes = array();
	
	protected $iBreedte;
	protected $iGrootte;	
	protected $iHoogte;

	protected $sMap;
	
	############################### Magic Methods (Alfabetisch)
	public function __construct($sMap)
	{
		$this->SetMap($sMap);
	}
	
	############################### Method (Alfabetisch)
	protected function CheckMap()
	{
		if(is_dir($this->sMap))
		{
			@chmod($this->sMap, 0777);
		}
		else
		{
			if(!mkdir($this->sMap, 0755))
			{
				throw new Exception(__FILE__.' -> '.__CLASS__.' -> '.__FUNCTION__.' -> '.__LINE__.': map bestaat niet en kan niet worden gemaakt');
			}
		}
	}
	
	protected function PushError($sError)
	{
		$this->aErrors[] = $sError;
	}
	
	protected function ToBytes($sEenheid)
	{
		if($sEenheid == 'b')
		{
			$this->iGrootte = abs(ceil($this->iGrootte));
		}
		elseif($sEenheid == 'kb')
		{
			$this->iGrootte = abs(ceil($this->iGrootte * 1024));
		}
		elseif($sEenheid == 'mb')
		{
			$this->iGrootte = abs(ceil($this->iGrootte * 1024 * 1024));
		}
		else
		{
			throw new Exception(__FILE__.' -> '.__CLASS__.' -> '.__FUNCTION__.' -> '.__LINE__.': onbekende eenheid');
		}
	}
	
	public function UploadFile(array $aFile, $sNaam = '')
	{
		if(count($aFile) == 5)
		{
			if($aFile['error'] != 0)		//Geen fouten?
			{
				$this->PushError('Fout in bestand, waarschijnlijk vulde u niets in, probeer opnieuw.');
			}
			
			if(!empty($this->iGrootte))		//Is er een grootte opgegeven? Ja dan checken we hem
			{
				if($aFile['size'] > $this->iGrootte)
				{
					$this->PushError('Het bestand is te groot('.$aFile['size'].' bytes), de maximale grootte is '.$this->iGrootte.' bytes.');
				}
				elseif($aFile['size'] == 0)
				{
					$this->PushError('Het bestand is of veel te groot, of niet ingevuld.');
				}
			}
			
			if(!empty($this->iBreedte) || !empty($this->iHoogte) || count($this->aMimeTypes) != 0)	//Is er een breedte hoogte of mimetype opgegeven? Ja we checken ze, hier gaan we ervan uit dat het een plaatje is.
			{	
				if(($aTempInfo = getimagesize($aFile['tmp_name'])) === false)
				{
					$this->PushError('Van dit (type) bestand kan geen informatie verkregen worden.');
				}
				else
				{				
					list($iBreedte, $iHoogte, ,,) = $aTempInfo;
					if(!empty($this->iBreedte))
					{
						if($iBreedte > $this->iBreedte)
						{
							$this->PushError('Sorry, het plaatje is te breed('.$iBreedte.'), maximale breedte is '.$this->iBreedte.'.');	
						}
					}
					if(!empty($this->iHoogte))
					{
						if($iHoogte > $this->iHoogte)
						{
							$this->PushError('Sorry, het plaatje is te hoog('.$iHoogte.'), maximale hoogte is '.$this->iHoogte.'.');	
						}
					}
					if(count($this->aMimeTypes) != 0)
					{
						if(!in_array(strtolower($aTempInfo['mime']), $this->aMimeTypes))
						{
							$this->PushError('Dit type afbeelding('.$aTempInfo['mime'].') wordt niet ondersteund.');
						}
					}
				}
			}
			
			if(count($this->aExt) != 0)			//Extensie opgegeven? Ja dan checken we die
			{				
				if(($aTempInfo = pathinfo($aFile['name'])) === false)
				{
					$this->PushError('Onbekende fout.');
				}
				
				$sExt = ((isset($aTempInfo['extension'])) ? ($aTempInfo['extension']) : ('onbekend'));
				if(!in_array(strtolower($sExt), $this->aExt))
				{
					$this->PushError('Sorry, bestanden met de extensie ('.$sExt.') mogen niet worden geupload.');
				}
			}
			
			if(count($this->GetErrors()) == 0)	//Geen errors ontstaan? We gaan uploaden, eventueel hernoemen we het bestand nog.
			{
				if(is_uploaded_file($aFile['tmp_name']))
				{
					$sPath = $this->sMap.strtolower($aFile['name']);
					if(move_uploaded_file($aFile['tmp_name'], $sPath))
					{
						if(!empty($sNaam))
						{
							$sNieuweNaam = $this->sMap.$sNaam.'.'.end(explode('.', $sPath));
							if(!rename($sPath, $sNieuweNaam ))
							{
								unlink($sPath);
								$this->PushError('Kon bestand niet hernoemen, bestand is van de server verwijderd, probeer opnieuw.');
								return false;
							}
							else
							{
								return $sNieuweNaam;
							}
						}
						else
						{							
							return $sPath;
						}
					}
					else
					{
						$this->PushError('Fout bij het uploaden.');
						return false;
					}
				}
				else
				{
					$this->PushError('De waardes graag via het formulier invullen.');
					return false;
				}
			}
			else
			{
				return false;
			}
		}		
		else
		{
			throw new Exception(__FILE__.' -> '.__CLASS__.' -> '.__FUNCTION__.' -> '.__LINE__.': Verkeerde array');
		}
	}
	
	############################### Setters (Alfabetisch)
	public function SetExtensions(array $aExt)
	{
		foreach($aExt as $sExt)
		{	
			$this->aExt[] = strtolower($sExt);
		}
	}
	
	public function SetFormaat($iBreedte, $iHoogte)
	{
		if(ctype_digit($iBreedte) && ctype_digit($iHoogte))
		{
			$this->iBreedte = $iBreedte;
			$this->iHoogte = $iHoogte;
		}
		else
		{
			throw new Exception(__FILE__.' -> '.__CLASS__.' -> '.__FUNCTION__.' -> '.__LINE__.': Cijfer vereist bij beide parameters');
		}
	}
	
	public function SetGrootte($iGrootte, $sEenheid = 'b')
	{
		if(is_numeric($iGrootte))
		{
			$this->iGrootte = $iGrootte;
			$this->ToBytes($sEenheid);
		}
		else
		{
			throw new Exception(__FILE__.' -> '.__CLASS__.' -> '.__FUNCTION__.' -> '.__LINE__.': Cijfer vereist als eerste parameter');
		}
	}
	
	public function SetMap($sMap)
	{
		if(substr($sMap, -1, 1) == '/')
		{
			$this->sMap = $sMap;
		}
		else
		{
			$this->sMap = $sMap.'/';
		}
		$this->CheckMap();
	}
	
	public function SetMimeTypes(array $aMimes)
	{
		foreach($aMimes as $sMime)
		{	
			$this->aMimeTypes[] = strtolower($sMime);
		}
	}
	
	############################### Getters (Alfabetisch)	
	public function GetErrors()
	{
		return $this->aErrors;
	}
	
	public function GetExtensions()
	{
		return $this->aExt;
	}
	
	public function GetFormaat()
	{
		return array('breedte' => $this->sBreedte, 'hoogte' => $sHoogte);
	}
	
	public function GetGrootte()
	{
		return $this->sGrootte;
	}
	
	public function GetMap()
	{
		return $this->sMap;
	}
	
	public function GetMimeTypes()
	{
		return $this->aMimeTypes;
	}
}
?>[/code]

Voorbeeld
[code]
<?php
define('DEBUG', true);
error_reporting(E_ALL);
ini_set('display_errors', DEBUG);
 
$sContent = NULL;
$sTitel = NULL;

include('./class.php');

$sTitel .= 'D-lightweb | Phphulp | Voorbeeld FileUploadClass';

try
{	
	$oUpload = new UploadFile(dirname(__FILE__).'/uploads/');
	$oUpload->SetGrootte('50', 'kb');
	$oUpload->SetFormaat('800', '800');
	$oUpload->SetMimeTypes(array('image/jpeg', 'image/gif'));
	$oUpload->SetExtensions(array('jpg', 'jpeg', 'gif'));
			
	if($_SERVER['REQUEST_METHOD'] == 'POST')
	{
		if(($sPath = $oUpload->UploadFile($_FILES['fFoto'], rand(1000,9999).time())) !== false)
		{
			$sContent .= '<p style="font-family:Verdana; font-size:11px;">Het lukte! ';
			$sContent .= 'Het bestand staat nu hier: '.$sPath;
			$sContent .= '<br /><a style="color:black;" href="'.basename(__FILE__).'">Ga terug</a></p>';
		}
		else
		{
			$sContent .=  '<span style="font-family:Verdana; padding:5px; font-size:12px; font-weight:bold; display:block; color:red;">Er ging wat fout:</span>';
			foreach($oUpload->GetErrors() as $sError)
			{
				$sContent .= '<span style="color:red; padding:5px; font-family:Verdana; font-size:11px; display:block;">'.$sError.'</span>';
			}
		}
	}
	
	$sContent .= '<form action="'.basename(__FILE__).'" method="post" style="padding:5px; margin:5px; border: 1px solid #DDD; width:400px;" enctype="multipart/form-data" name="fForm"><p style="margin:0px; padding:5px;"><input style="width:100%;" type="file" name="fFoto" id="fFoto" /></p><p style="margin:0px; padding:5px;"><input type="submit" style="border:1px solid #7F9DB9; padding:5px; width:100%; background:white;" value="verzenden" name="fSubmit" /></p></form>';
}
catch(Exception $oException)
{
	if(DEBUG)
	{
		$sContent = $oException->getMessage();
	}
	else
	{
		$sContent .= 'Pagina kon niet geladen worden, is dat ff klote...';
	}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><?php echo ((isset($sTitel)) ? ($sTitel) : ('Geen titel')); ?></title>
</head>

<body>
<?php
echo ((isset($sContent)) ? ($sContent) : ('Geen inhoud voor deze pagina'));
?>
</body>
</html>
[/code]

Reacties

0
Nog geen reacties.