Skip to content

Instantly share code, notes, and snippets.

@lebalz
Created May 10, 2020 10:25
Show Gist options
  • Save lebalz/a94944fd008a317386fb9415b5814f17 to your computer and use it in GitHub Desktop.
Save lebalz/a94944fd008a317386fb9415b5814f17 to your computer and use it in GitHub Desktop.
Upload images with php
<?php
// definiere Funktion "endsWith" falls sie nicht bereits definiert wurde
if (!function_exists('endsWith')) {
/**
* endet $string mit $endString?
* @param string [String]
* @param endString [String]
* @return [boolean]
*/
function endsWith($string, $endString)
{
$len = strlen($endString);
if ($len == 0) {
return true;
}
return (substr($string, -$len) === $endString);
}
}
if (!function_exists('upload_image')) {
/**
* @param form_field_name [string] der Name des Input-Feldes im Formular
* e.g. für <input type="file" name="image">
* wäre es 'image'
* @param upload_folder [string] Pfad zum Upload-Ordner, e.g. 'uploads/'
* @return [string] Pfad zum hochgeladenen Bild
*/
function upload_image($form_field_name, $upload_folder)
{
// upload code from https://www.php-einfach.de/php-tutorial/dateiupload/
$filename = pathinfo($_FILES[$form_field_name]['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($_FILES[$form_field_name]['name'], PATHINFO_EXTENSION));
// Überprüfung der Dateiendung
$allowed_extensions = array('png', 'jpg', 'jpeg', 'gif');
if (!in_array($extension, $allowed_extensions)) {
die("Ungültige Dateiendung. Nur png, jpg, jpeg und gif-Dateien sind erlaubt: " . $extension);
}
// Überprüfung der Dateigröße
$max_size = 5000 * 1024; //5 MB
if ($_FILES[$form_field_name]['size'] > $max_size) {
die("Bitte keine Dateien größer 5MB hochladen");
}
/**
* Überprüfung dass das Bild keine Fehler enthält
*/
// Die exif_imagetype-Funktion erfordert die exif-Erweiterung auf dem Server
if (function_exists('exif_imagetype')) {
$allowed_types = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detected_type = exif_imagetype($_FILES[$form_field_name]['tmp_name']);
if (!in_array($detected_type, $allowed_types)) {
die("Nur der Upload von Bilddateien ist gestattet");
}
}
if (!endsWith($upload_folder, '/')) {
$upload_folder = $upload_folder + '/';
}
//Pfad zum Upload
$new_path = $upload_folder . $filename . '.' . $extension;
/**
* Dateinamen für das Bild setzen
*/
// Falls Datei existiert, hänge eine Zahl an den Dateinamen
if (file_exists($new_path)) {
$id = 1;
do {
$new_path = $upload_folder . $filename . '_' . $id . '.' . $extension;
$id = $id + 1;
} while (file_exists($new_path));
}
// Alles okay, verschiebe Datei an neuen Pfad
move_uploaded_file($_FILES[$form_field_name]['tmp_name'], $new_path);
return $new_path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment