PHP - Upload Formular

Aus Wikizone
Wechseln zu: Navigation, Suche

Siehe auch[Bearbeiten]

PHP - Upload
ProcessWire Upload Formular

Beispiel 1 - Upload Formular ohne AJAX[Bearbeiten]

http://php.net/manual/de/features.file-upload.post-method.php

HTML[Bearbeiten]

Formular mit

enctype="multipart/form-data"

und

<input type="file" name="uploaded_file">
<!DOCTYPE html>
<html>
<body>
<form method="POST" name="email_form_with_php"
action="upload.php" enctype="multipart/form-data"> 
 
<label for='name'>Name: </label>
<input type="text" name="name" >
 
<label for='email'>Email: </label>
<input type="text" name="email" >
 
<label for='message'>Message:</label>
<textarea name="message"></textarea>
 
<label for='uploaded_file'>Select A File To Upload:</label>
<input type="file" name="uploaded_file">
 
<input type="submit" value="Submit" name='submit'>
</form>
</body>
</html>

Das maxfilesize feld ist hier nicht drin. Es ersetzt keine servervalidierung hilft soll aber dem user schon vor dem upload helfen zu erkennen, wenn er ein zu großes File nimmt - theoretisch denn in der Praxis unterstützt es kein Browser.

PHP[Bearbeiten]

Auf die frisch hochgeladenen Dateien kann über die Servervariable $_FILES zugegriffen werden

<?php 
echo("<pre>");
$upload_ok = 1;
$errors = '';
$strDate=date("Y-m-d_H:i:s_");

/***** CONFIGURATION PART  *****/
$actual_path = dirname($_SERVER["SCRIPT_FILENAME"]);
$upload_folder = $actual_path.'/uploads/';
$max_allowed_file_size = 10000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");


//FILE INFOS
/*
echo('$_FILES Variable');
var_dump($_FILES);
echo('$_SERVER Variable');
var_dump($_SERVER);
*/

$name_of_uploaded_file = $strDate.basename($_FILES['uploaded_file']['name']);
 
//get the file extension of the file
$type_of_uploaded_file =
	substr($name_of_uploaded_file,
	strrpos($name_of_uploaded_file, '.') + 1);
 
$size_of_uploaded_file =
	$_FILES["uploaded_file"]["size"]/1024;//size in KBs



/***** VALIDATE UPLOADED FILE *****/
//Size validation
if($size_of_uploaded_file > $max_allowed_file_size )
{
	$errors .= "<br> Size of file should be less than $max_allowed_file_size";
	$upload_ok = 0;
}
 
//File extension validation
$allowed_ext = false;
for($i=0; $i < sizeof($allowed_extensions); $i++)
{
	if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
	{
		$allowed_ext = true;
	}
}
 
if(!$allowed_ext)
{
	$errors .= "<br> The uploaded file is not supported file type. ".
	" Only the following file types are supported: ".implode(',',$allowed_extensions);
	$upload_ok = 0;
}

/***** COPY TEMPORARY UPLOADED FILE *****/
$target_path_and_name = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($upload_ok && is_uploaded_file($tmp_path))
{
	if(!copy($tmp_path,$target_path_and_name))
	{
		$errors .= '<br>error while copying the uploaded file';
		$upload_ok = 0;
	}
}

if (!$upload_ok) echo $errors;
else echo("upload ok");
echo("</pre>");
?>

Beispiel 2 - Upload Formular mit Mailversand als Attachment[Bearbeiten]

PHP Ergänzung:

/***** SEND MAIL *****/
$to = '"Stephan Schlegel" <schlegel@geo-bit.de>';
print_r($to);
$subject = 'TESTMAIL';
$body = 'Testmail mit Attachment';
$filename = $name_of_uploaded_file;

if($upload_ok){
	if(sendMail($to,$subject,$body,$tmp_path,$filename)){
		echo("Mail wurde versendet");
	}else{
		echo("Mailversand nicht erfolgreich.");
	}
}

function sendMail($to,$subject,$body,$att,$filename){
	$success=1;

	$from_mail = 'noreply@'.$_SERVER['SERVER_NAME'];
	$from = '"Testmailer" <'.$from_mail.'>';
	$headers="";
	$mid = md5( time() ); // Multipart Mail ID (Trenner)
	$attachment = chunk_split( base64_encode( file_get_contents( $att ) ) );
	
	$headers .= 'X-Mailer: PHP/'.phpversion()."\r\n";
	$headers .='From: '.$from."\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-Type: multipart/mixed; boundary=\"".$mid."\"\r\n\r\n";
	$headers .= "This is a multi-part message in MIME format.\r\n";
	$headers .= "--".$mid."\r\n";
	
	
	//attachment
	$content_type= getMimeType($att);
	$headers .= "Content-Type: ".$content_type."; name=\"".$filename."\"\r\n";
	$headers .= "Content-Transfer-Encoding: base64\r\n";
	$headers .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
	$headers .= $attachment."\r\n\r\n";
	$headers .= "--".$mid."--";
	$addParams = '-f'.$from_mail;
	print_r($addParams);
	$success = mail($to, $subject, $body, $headers,$addParams);
		return $success;
}

function getMimeType($file_abspath_and_name){
	$mimeType="";
	$finfo = finfo_open(FILEINFO_MIME_TYPE);
	$mimeType = finfo_file($finfo, $file_abspath_and_name);
	finfo_close($finfo);
	return $mimeType;
}

// alternative Funktion zu getMimeType wenn PHP Version zu niedrig, buggy oder deaktiviert
function mime_type($file) {

    // there's a bug that doesn't properly detect
    // the mime type of css files
    // https://bugs.php.net/bug.php?id=53035
    // so the following is used, instead
    // src: http://www.freeformatter.com/mime-types-list.html#mime-types-list

    $mime_type = array(
        "3dml" => "text/vnd.in3d.3dml",
        "3g2" => "video/3gpp2",
        "3gp" => "video/3gpp",
        "7z" => "application/x-7z-compressed",
        "aab" => "application/x-authorware-bin",
        "aac" => "audio/x-aac",
        "aam" => "application/x-authorware-map",
        "aas" => "application/x-authorware-seg",
        "abw" => "application/x-abiword",
        "ac" => "application/pkix-attr-cert",
        "acc" => "application/vnd.americandynamics.acc",
        "ace" => "application/x-ace-compressed",
        "acu" => "application/vnd.acucobol",
        "adp" => "audio/adpcm",
        "aep" => "application/vnd.audiograph",
        "afp" => "application/vnd.ibm.modcap",
        "ahead" => "application/vnd.ahead.space",
        "ai" => "application/postscript",
        "aif" => "audio/x-aiff",
        "air" => "application/vnd.adobe.air-application-installer-package+zip",
        "ait" => "application/vnd.dvb.ait",
        "ami" => "application/vnd.amiga.ami",
        "apk" => "application/vnd.android.package-archive",
        "application" => "application/x-ms-application",
        // etc...
        // truncated due to Stack Overflow's character limit in posts
    );

    $extension = \strtolower(\pathinfo($file, \PATHINFO_EXTENSION));

    if (isset($mime_type[$extension])) {
        return $mime_type[$extension];
    } else {
        throw new \Exception("Unknown file type");
    }

}