Hoi beste PHP'ers,
heb me toch nog eens verdiept in het schrijven van een class om files te uploaden.

Allereerst het script: (upload.php)
<?php

/**************************************************\
	Deze class is gemaakt door Günther Peeters
	en is vrij voor gebruik
\**************************************************/

class upload {
	public $error = array(), $succes = array('code' => '0', 'message' => 'Not Executed');
	private $maxWidth, $maxHeight, $resizeImage, $maxSize, $allowedExtention, $notAllowedExtention, $newName, $folder, $autoRename, $permissie;

	// Construct
	function __construct(){
	}

	/**************************************************\
		Instellingen
	\**************************************************/
	// Maximum breedde van de afbeelding
	public function setMaxWidth($maxWidth = NULL){
		$this->maxWidth = isset($maxWidth) ? $maxWidth : NULL;
	}

	// Maximum hoogte van de afbeelding
	public function setMaxHeight($maxHeight = NULL){
		$this->maxHeight = isset($maxHeight) ? $maxHeight : NULL;
	}

	// Afbeelding aanpassen bij upload
	public function resize($status = NULL){
		if ($status === 1 || $status === 'on' || $status === true){
			$this->resizeImage = 1;
		}
	}

	// Maximum grootte van de file
	public function setMaxSize($setMaxSize = NULL){
		$this->maxSize = isset($setMaxSize) ? $setMaxSize : NULL;
	}

	// Toegestane extenties
	public function allowedExtention($extention = NULL){
		if (isset($this->notAllowedExtention) && in_array($extention, $this->notAllowedExtention)){
			$this->error['extentionAllowed'][$extention] = 'Already Exists In Not Allowed';
		} else {
			$this->allowedExtention = isset($this->allowedExtention) ? $this->allowedExtention : array();
			if (!in_array($extention, $this->allowedExtention)){
				$this->allowedExtention[] = isset($extention) ? $extention : NULL;
			}
		}
	}

	// Niet toegestane extenties
	public function notAllowedExtention($extention = NULL){
		if (isset($this->allowedExtention) && in_array($extention, $this->allowedExtention)){
			$this->error['extentionNotAllowed'][$extention] = 'Already Exists In Not Allowed';
		} else {
			$this->notAllowedExtention = isset($this->notAllowedExtention) ? $this->notAllowedExtention : array();
			if (!in_array($extention, $this->notAllowedExtention)){
				$this->notAllowedExtention[] = isset($extention) ? $extention : NULL;
			}
		}
	}

	// Nieuwe naam geven aan de upload file
	public function setNewName($name = NULL, $autoRename = NULL){
		if ($autoRename === 1 || $autoRename === 'on' || $autoRename === true){
			$this->autoRename = 1;
		} else {
			$this->autoRename = 0;
		}
		$this->newName = isset($name) ? $name : NULL;
	}

	// Uploaden naar folder
	public function setFolder($folder = NULL){
		$folder = ltrim($folder, '/');
		$folder = rtrim($folder, '/');
		if (is_dir($folder)){
			$this->folder = $folder;
		} else {
			$this->error['folder'] = 'Folder Not Exists (<a href="'.$folder.'">'.$folder.'</a>)';
		}
	}

	/**************************************************\
		Controle van File
	\**************************************************/
	public function execute($file = NULL){
		if (isset($file['error']) && $file['error'] === 0){
			if (!empty($file)){

				// Controleer extentie
				$tmp = explode('.', $file['name']);
				$extension = end($tmp);
				if ((isset($this->allowedExtention) && !in_array($extension, $this->allowedExtention)) || (isset($this->notAllowedExtention) && in_array($extension, $this->notAllowedExtention))){
					$this->error['extention'] = 'File Extention Not Allowed ('.$extension.')';
				}

				// Controleer grootte van de file
				if (isset($this->maxSize) && $file['size'] > $this->maxSize){
					$this->error['maxSize']['message'] = 'File Too Big';
					$this->error['maxSize']['allowed'] = $this->setMaxSize;
					$this->error['maxSize']['file'] = $file['size'];
				}

				// Controleer bestaande file
				$this->folder = isset($this->folder) ? $this->folder : NULL;
				$newName = isset($this->newName) ? $this->newName.'.'.$extension : $file['name'];
				if (file_exists($this->folder.'/'.$newName)){
					$this->autoRename = isset($this->autoRename) ? $this->autoRename : 0;
					// Automatisch hernoemen als file al bestaat
					if ($this->autoRename == 1){
						$newName = str_replace('.'.$extension, '', $newName);
						$makeNewName = $newName;
						while (file_exists($this->folder.'/'.$makeNewName.'.'.$extension)){
							$makeNewName = $newName.'_'.time();
						}
						$newName = $makeNewName.'.'.$extension;
					} else {
						$this->error['exists'] = 'File Already Exists';
					}
				}

				// Controleer afbeelding
				if (strpos($file['type'], 'image') === 0 && (isset($this->maxWidth) || isset($this->maxHeight))){
					list ($width, $height) = getimagesize($file['tmp_name']);
					if (isset($this->resizeImage) && $this->resizeImage === 1){
						if ($width > $this->maxWidth || $height > $this->maxHeight){
							// Controleer Extentie
							$tmp = explode('.', $file['name']);
							$extension = end($tmp);
							$extension = isset($extension) ? strtolower($extension) : NULL;
							switch ($extension){
								case 'jpg':
								$src = @imagecreatefromjpeg($file['tmp_name']);
								break;
								case 'jpeg':
								$src = @imagecreatefromjpeg($file['tmp_name']);
								break;
								case 'png':
								$src = @imagecreatefrompng($file['tmp_name']);
								break;
								default:
								$src = @imagecreatefromgif($file['tmp_name']);
								break;
							}
							@imagealphablending($src, true);
							// Controleer breedde
							if ($width > $this->maxWidth){
								$newWidth = $this->maxWidth;
								$newHeight = round(($height / $width) * $this->maxWidth);
							}
							// Controleer hoogte
							if ($height > $this->maxHeight){
								$newWidth = round(($width / $height) * $this->maxHeight);
								$newHeight = $this->maxHeight;
							}
							// Afbeelding aanpassen
							$tmpImg = @imagecreatetruecolor($newWidth, $newHeight);
							@imagealphablending($tmpImg, false);
							@imagesavealpha($tmpImg, true);
							@imagecopyresampled($tmpImg, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
							switch ($extension){
								case 'jpg':
								@imagejpeg($tmpImg, $file['tmp_name'], 100);
								break;
								case 'jpeg':
								@imagejpeg($tmpImg, $file['tmp_name'], 100);
								break;
								case 'png':
								imagepng($tmpImg, $file['tmp_name'], 9);
								break;
								default:
								imagegif($tmpImg, $file['tmp_name'], 100);
								break;
							}
							@imagedestroy($src);
							@imagedestroy($tmpImg);
						}
					} else {
						// Breedde
						if ($width > $this->maxWidth){ $this->error['maxWidth']['message'] = 'Image width to big'; }
						if ($width > $this->maxWidth){ $this->error['maxWidth']['allowed'] = $this->maxWidth; }
						if ($width > $this->maxWidth){ $this->error['maxWidth']['image'] = $width; }
						// Hoogte
						if ($height > $this->maxHeight){ $this->error['maxHeight']['message'] = 'Image height to big'; }
						if ($height > $this->maxHeight){ $this->error['maxHeight']['allowed'] = $this->maxHeight; }
						if ($height > $this->maxHeight){ $this->error['maxHeight']['image'] = $height; }
					}
				}

				// Controleer permissie
				$this->permissie = (fileperms($this->folder) & 0x0002) ? 1 : 0;
				if ($this->permissie !== 1){ $this->error['permission'] = 'No permission to upload file ('.substr(sprintf('%o', fileperms($this->folder)), -4).')'; }

				// Geen fouten gevonden
				if (count(array_keys($this->error, true)) === 0){
					// Start upload file
					if (!move_uploaded_file($file['tmp_name'], $this->folder.'/'.$newName)){
						$this->succes = array('code' => '0', 'message' => 'Failed');
					} else {
						$this->succes = array('code' => '1', 'message' => 'File Upload Succeed: <a href="'.$this->folder.'/'.$newName.'">'.$this->folder.'/'.$newName.'</a>', 'filename' => $newName);
					}
				}

			} else {
				// Geen file mee gegeven
				$this->error['empty'] = 'No File Found';
			}
		} else {
			// Alle andere fouten
			$this->error['file'] = 'No File Found';
		}
	}
}

?>

De werking:
<?php

/**************************************************\
	Include upload-file
\**************************************************/
require_once('upload.php');

/**************************************************\
	Instellingen
\**************************************************/
// Start een nieuw upload
$upload = new upload;
// Maximum toegelaten Breedte en Hoogte
$upload->setMaxWidth(100);
$upload->setMaxHeight(100);
// Afbeelding resizen als het groter is dan toegelaten (1, on, true => aan)
$upload->resize(1);
// Afbeelding een nieuwe naam geven, indien naam al bestaat een timestamp toevoegen
$upload->setNewName('test', 1);
// Alleen afbeeldingen met jpg toestaan
$upload->allowedExtention('jpg');
$upload->allowedExtention('jpeg');
// Uploaden naar folder images
$upload->setFolder('images');

/**************************************************\
	Controleer POST
\**************************************************/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])){
	// Upload uitvoeren
	$upload->execute($_FILES['file']);
}

/**************************************************\
	Toon meldingen
\**************************************************/
print '<pre>';
print_r($upload);
print '</pre>';

/**************************************************\
	Een simpel form als voorbeeld
\**************************************************/
print '<form action="" method="post" enctype="multipart/form-data">';
print '	<input type="file" name="file" id="file">';
print '	<input type="submit" name="submit" id="submit" value="upload">';
print '</form>';

?>


Woordje uitleg:
Een nieuwe upload starten
$upload = new upload;

Voor afbeeldingen:
$upload->setMaxWidth(getal); // Zet maximum breedte van de afbeelding
$upload->setMaxHeight(getal); // Zet maximum hoogte van de afbeelding
$upload->resize(waarde); // Waarde = 1, true of on :: Hierbij wordt de afbeelding aangepast aan de ingegeven breedte en hoogte of er wordt een foutmelding gegeven

Maximum grootte van de file:
$upload->setMaxSize(getal);

Extenties toestaan of weigeren:
$upload->allowedExtention('extention'); // Dit laat de extentie toe
$upload->notAllowedExtention('extention'); // Dit laat de extentie niet toe

Benaming:
$upload->setNewName('name', status);
name: Geef de file deze naam
status: 1, on, true :: Als er al een file bestaat automatisch hernoemen met een timestamp
status: 0, off, enz... :: Toont de foutmelding dat deze file al bestaat

Uploaden naar:
$upload->setFolder('path/to/folder'); // Geen verder uitleg

Uploaden uitvoeren:
$upload->execute($_FILES['file']);

Foutmeldingen:
$upload->error
Er worden foutmeldingen getoond bij alles wat niet correct is.

Uw gedacht is goud waard!
Als je ideeën of opmerkingen hebt, hoor ik het graag.
Niemand geen opmerkingen hierover?
Tweetal puntjes die ik op het oog opmerk;
- Regel 183 - 185 en 187 - 189 behoeven niet zoveel if-else constructies; de vergelijking is immers steeds hetzelfde.
- Mijdt het gebruik van '@Functienaam', dit is beter op te lossen met fatsoenlijkere foutenafhandeling
Ok, ik heb de regels 183 tot 185 en 187 tot 189 aangepast, dat was blijkbaar iets wat ik vergeten heb aan te passen tijdens mijn test van het script.

Als ik de @ weghaal wil het om 1 of andere reden op sommige servers niet werken... heb naar oplossingen gezocht met google en kom steeds weer uit dat ik er een @ voor moet zetten.
Begrijp ik het goed dat dit script werkt, maar dat je toch nog opmerkingen wil, van wie iets vindt dat beter kan?


allowedExtention verdient de aandacht.
Om te beginnen, allowedExtention en notAllowedExtention ... dat is niet de bedoeling.
Als je een lijst hebt met toegelaten extensies, heb je niet nog een lijst nodig met het omgekeerde. Alles wat niet in de lijst allowedExtention staat, is per definitie not allowed.
(Een lijst maken met extensies die ongewenst zijn, zou nogal een lange lijst zijn)

Ik zou dit trouwens regelen met de functie

public function setAllowedExtentions(array $extensions)
Dus, bij de werking, iets als
$upload->setAllowedExtentions(array('jpg', 'jpeg', 'png', 'gif'));

Bij het evalueren van de extensie moet je trouwens nog regelen dat niet wordt gezien naar de de hoofdletters.
Waarschijnlijk best iets als:

$extension = strtolower(end($tmp)); // lijn 95
Ik heb dus notAllowedExtentions verwijderd en de allowedExtentions gewijzigd
<?php
	// Toegestane extenties
	public function setAllowedExtention($extention){
		if (is_array($extention)){
			foreach ($extention as $ext){
				if (!in_array($ext, $this->allowedExtention)){
					$this->allowedExtention[] = isset($ext) ? strtolower($ext) : NULL;
				}
			}
		} else {
			if (!in_array($extention, $this->allowedExtention)){
				$this->allowedExtention[] = isset($extention) ? strtolower($extention) : NULL;
			}
		}
	}
?>
Lijn 95 is ook aangepast met strtolower

Ik ben me ook aan denken geweest om $succes te wijzigen naar $error['succes']. Wat zou hier het beste voor zijn?
De nieuwe code:
<?php

/**************************************************\
	Deze class is gemaakt door Günther Peeters
	met behulp van PHPHULP.NL (http://www.phphulp.nl/)
\**************************************************/

class upload {

	/* Public */
	public
		$error = array(),
		$succes = array(
			'code' => '0',
			'message' => 'Not Executed'
		);

	/* Private */
	private
		$maxWidth,
		$maxHeight,
		$resizeImage,
		$maxSize,
		$allowedExtention = array(
		),
		$newName,
		$folder,
		$autoRename,
		$renameType,
		$permissie;

	// Construct
	public function __construct(){
	}

	/**************************************************\
		Instellingen
	\**************************************************/
	// Maximum breedte van de afbeelding
	public function setMaxWidth($maxWidth = NULL){
		$this->maxWidth = isset($maxWidth) ? $maxWidth : NULL;
	}

	// Maximum hoogte van de afbeelding
	public function setMaxHeight($maxHeight = NULL){
		$this->maxHeight = isset($maxHeight) ? $maxHeight : NULL;
	}

	// Afbeelding aanpassen bij upload
	public function resize($status = NULL){
		if ($status === 1 || $status === 'on' || $status === true){
			$this->resizeImage = 1;
		}
	}

	// Maximum grootte van de file
	public function setMaxSize($setMaxSize = NULL){
		$this->maxSize = isset($setMaxSize) ? $setMaxSize : NULL;
	}

	// Toegestane extenties
	public function setAllowedExtention($extention){
		if (!is_array($extention)) { $extention = func_get_args(); }
		$extention = array_map('strtolower', $extention);
		foreach ($extention as $ext){
			if (!in_array($ext, $this->allowedExtention)){
				$this->allowedExtention[] = $ext;
			}
		}
	}

	// Nieuwe naam geven aan de upload file
	public function setNewName($name = NULL, $autoRename = NULL){
		if (!empty($autoRename)){
			$this->autoRename = 1;
			if ($autoRename === 'date'){
				$this->renameType = 'date';
			} elseif ($autoRename === 'alphabet'){
				$this->renameType = 'alphabet';
			} else {
				$this->renameType = 'numeric';
			}
		} else {
			$this->autoRename = 0;
		}
		$this->newName = !empty($name) ? $name : NULL;
	}

	// Uploaden naar folder
	public function setFolder($folder = NULL){
		$folder = ltrim($folder, '/');
		$folder = rtrim($folder, '/');
		if (is_dir($folder)){
			$this->folder = $folder;
		} else {
			$this->error['folder'] = 'Folder Not Exists (<a href="'.$folder.'">'.$folder.'</a>)';
		}
	}

	/**************************************************\
		Controle van File
	\**************************************************/
	public function execute($file = NULL){
		if (isset($file['error']) && $file['error'] === 0){
			if (!empty($file)){

				// Ophalen van extentie
				$tmp = explode('.', $file['name']);
				$extension = end($tmp);
				$extension = strtolower($extension);

				// Controleer extentie
				if ((isset($this->allowedExtention) && !in_array($extension, $this->allowedExtention)) || (isset($this->notAllowedExtention) && in_array($extension, $this->notAllowedExtention))){
					$this->error['extention'] = 'File Extention Not Allowed ('.$extension.')';
				}

				// Controleer grootte van de file
				if (isset($this->maxSize) && $file['size'] > $this->maxSize){
					$this->error['maxSize']['message'] = 'File Too Big';
					$this->error['maxSize']['allowed'] = $this->setMaxSize;
					$this->error['maxSize']['file'] = $file['size'];
				}

				// Controleer bestaande file
				$this->folder = isset($this->folder) ? $this->folder : NULL;
				$newName = isset($this->newName) ? $this->newName.'.'.$extension : $file['name'];
				if (file_exists($this->folder.'/'.$newName)){
					$this->autoRename = isset($this->autoRename) ? $this->autoRename : 0;
					// Automatisch hernoemen als file al bestaat
					if ($this->autoRename === 1){
						$newName = str_replace('.'.$extension, '', $newName);
						$makeNewName = $newName;
						if ($this->renameType === 'date'){
							while (file_exists($this->folder.'/'.$makeNewName.'.'.$extension)){
								$makeNewName = $newName.'_'.time();
							}
						} elseif ($this->renameType === 'alphabet'){
							$alphabet = 'abcedfghijklmnopqrstuvwxyz';
							$count = 0;
							$add = '';
							while (file_exists($this->folder.'/'.$makeNewName.'.'.$extension)){
								$makeNewName = $newName.'_'.$add.substr($alphabet, $count, 1);
								$count++;
								if ($count == 26){
									$count = 0;
									$add .= 'a';
								}
							}
						} else {
							$numeric = 0;
							while (file_exists($this->folder.'/'.$makeNewName.'.'.$extension)){
								$numeric++;
								$makeNewName = $newName.'_'.$numeric;
							}
						}
						$newName = $makeNewName.'.'.$extension;
					} else {
						$this->error['exists'] = 'File Already Exists';
					}
				}

				// Controleer afbeelding
				if (strpos($file['type'], 'image') === 0 && (isset($this->maxWidth) || isset($this->maxHeight))){
					list ($width, $height) = getimagesize($file['tmp_name']);
					if (isset($this->resizeImage) && $this->resizeImage === 1){
						if ($width > $this->maxWidth || $height > $this->maxHeight){
							// Controleer Extentie
							$tmp = explode('.', $file['name']);
							$extension = end($tmp);
							$extension = isset($extension) ? strtolower($extension) : NULL;
							switch ($extension){
								case 'jpg':
								$src = @imagecreatefromjpeg($file['tmp_name']);
								break;
								case 'jpeg':
								$src = @imagecreatefromjpeg($file['tmp_name']);
								break;
								case 'png':
								$src = @imagecreatefrompng($file['tmp_name']);
								break;
								default:
								$src = @imagecreatefromgif($file['tmp_name']);
								break;
							}
							@imagealphablending($src, true);
							// Controleer breedte
							if ($width > $this->maxWidth){
								$newWidth = $this->maxWidth;
								$newHeight = round(($height / $width) * $this->maxWidth);
							}
							// Controleer hoogte
							if ($height > $this->maxHeight){
								$newWidth = round(($width / $height) * $this->maxHeight);
								$newHeight = $this->maxHeight;
							}
							// Afbeelding aanpassen
							$tmpImg = @imagecreatetruecolor($newWidth, $newHeight);
							@imagealphablending($tmpImg, false);
							@imagesavealpha($tmpImg, true);
							@imagecopyresampled($tmpImg, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
							switch ($extension){
								case 'jpg':
								@imagejpeg($tmpImg, $file['tmp_name'], 100);
								break;
								case 'jpeg':
								@imagejpeg($tmpImg, $file['tmp_name'], 100);
								break;
								case 'png':
								imagepng($tmpImg, $file['tmp_name'], 9);
								break;
								default:
								imagegif($tmpImg, $file['tmp_name'], 100);
								break;
							}
							@imagedestroy($src);
							@imagedestroy($tmpImg);
						}
					} else {
						// Breedte foutmelding
						if ($width > $this->maxWidth){
							$this->error['maxWidth']['message'] = 'Image width to big';
							$this->error['maxWidth']['allowed'] = $this->maxWidth;
							$this->error['maxWidth']['image'] = $width;
						}
						// Hoogte foutmelding
						if ($height > $this->maxHeight){
							$this->error['maxHeight']['message'] = 'Image height to big';
							$this->error['maxHeight']['allowed'] = $this->maxHeight;
							$this->error['maxHeight']['image'] = $height;
							}
					}
				}

				// Controleer permissie
				$this->permissie = (fileperms($this->folder) & 0x0002) ? 1 : 0;
				if ($this->permissie !== 1){ $this->error['permission'] = 'No permission to upload file ('.substr(sprintf('%o', fileperms($this->folder)), -4).')'; }

				// Geen fouten gevonden
				if (count(array_keys($this->error, true)) === 0){
					// Start upload file
					if (!move_uploaded_file($file['tmp_name'], $this->folder.'/'.$newName)){
						$this->succes = array('code' => '0', 'message' => 'Failed'); // Upload niet geslaagt
					} else {
						// Upload gelukt
						$path = $this->folder.'/'.$newName;
						if ($checkImage = getimagesize($path)){
							$this->succes = array('code' => 1, 'message' => 'File Upload Succeed:<br><a href="'.$path.'"><img src="'.$path.'"></a>', 'filename' => $newName);
						} else {
							$this->succes = array('code' => 1, 'message' => 'File Upload Succeed: <a href="'.$path.'">'.$path.'</a>', 'filename' => $newName);
						}
					}
				}

			} else {
				// Geen file mee gegeven
				$this->error['empty'] = 'No File Found';
			}
		} else {
			// Alle andere fouten
			$this->error['file'] = $file;
		}
	}
}

?>
Update:
1) setAllowedExtention kan als volgend gebruikt worden:
- $upload->setAllowedExtention('jpg', 'png', 'gif');
- $upload->setAllowedExtention(array('jpg', 'png', 'gif'));

2) Automatisch hernoemen kan met date, numeric of alphabet

3) setNotAllowedExtention is verwijderd

4) Controle van extenties is verbetert (Kleine letters)

5) Het teveel aan if-else is verbetert

6) Bovenaan in de comment word PHPHULP vermeld :)

Uw gedacht:
Nog steeds zijn ideeën en opmerkingen steeds welkom

Reageren