- 04.02.2012, 00:50 #1Erfahrener Benutzer
- Registriert seit
- 12.10.2011
- Beiträge
- 202
- Renommee-Modifikator
- 0
Mehr Dateitypen akzeptieren ... ? Hallo,
Ich will mein Script so erweitern das alle Bilder-Dateitypen akzeptiert werden sprich PNG,JPEG,GIF,ICO,usw.
Hier das Script:
Mein Ansatz:Code:<?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/file/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } ?>
Fehler : Parse error: syntax error, unexpected T_LOGICAL_OR in /home/username/public_html/upload.php on line 8Code:<?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) or (($ext == "png") && ($_FILES["uploaded_file"]["type"] == "image/png") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/file/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } ?>
Danke
- 04.02.2012, 01:49 #2
Ich würde die erlaubten MIME-Typen in ein Array schreiben und dann in der originalen if-Bedingung mit in_array() prüfen statt auf einen einzigen String.
Wenn du die Dateiendung auch weiterhin mit prüfen möchtest, würde ich eine Datenstruktur mit den Assoziationen anlegen:
1. Bestimme MIME-Typ von Upload-Datei.PHP-Code:$allowed = array(
array(
'extensions' => array('jpeg', 'jpg'),
'mime' => 'image/jpeg'
),
array(
'extensions' => array('png'),
'mime' => 'image/png'
)
// usw.
);
2. Durchlaufe $allowed, bis MIME-Typ identisch mit dem eines Eintrags.
a) Falls zutreffend: Prüfe, ob Endung der Upload-Datei in 'extensions' vorkommt. Falls ja: Okay.
b) Falls nicht zutreffend: Fehler.
- 04.02.2012, 14:19 #3Erfahrener Benutzer
- Registriert seit
- 12.10.2011
- Beiträge
- 202
- Renommee-Modifikator
- 0
Code:<?php $extension = array("PNG", "JPEG", "JPG", "GIF"); if (in_array("PNG", $extension)) { echo "Ist PNG"; } if (in_array("JPG", $extension)) { echo "Ist JPG"; } ?>Hast du das so gemeint ? Und jetzt immer so weiter mit allen Image-Endungen oder ?
- 04.02.2012, 15:15 #4Erfahrener Benutzer
- Registriert seit
- 12.10.2011
- Beiträge
- 202
- Renommee-Modifikator
- 0
Habs schon danke...
- 04.02.2012, 16:52 #5
- 04.02.2012, 17:15 #6Erfahrener Benutzer
- Registriert seit
- 12.10.2011
- Beiträge
- 202
- Renommee-Modifikator
- 0
Gut ich poste es mal da ich deinen Rat sehr schätze
index.php
write_database.phpCode:<?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","10000"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="file/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { include('write_database.php'); echo "<h1>File Uploaded Successfully! $newname!</h1>"; } ?> <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" --> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><input type="file" name="image"></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form>
Noch ne Frage, was würdest du für werte abspeichern ?Code:<?php include('connect_database.php'); // prueft ob der submit button gedrueckt wurde if(isset($_POST['Submit'])) { // trim() entfernt die whitespaces vor und hinter dem string $filename = $image_name; $filesize = $_FILES['image']['size']; $extension = $extension; $date = date('Y-d-m'); // ueberpruefung ob die werte nicht leer sind if(!empty($filename) && !empty($filesize)) { // schreibe in die datenbank mysql_real_escape_string ist empfehlenswert um seine daten gegen sql injections abzusichern $sql_befehl = mysql_query("INSERT INTO file (fileid, filename, filesize, extension, date) VALUES ('', '".mysql_real_escape_string($image_name)."', '".mysql_real_escape_string($filesize)."', '".mysql_real_escape_string($extension)."', '".mysql_real_escape_string($date)."')"); } } ?>
Ich benötige die id,name,filesize,extension,date hab ich was vergessen was ich später noch brauchen könnte ?
Danke
- 04.02.2012, 19:51 #7
Keine Ahnung, welche Daten du später noch brauchst.
Ich habe mal ein wenig was gebastelt.
Ich hoffe, der meiste Code ist verständlich. Ich wüsste nicht, wo ich mit einer Erklärung beginnen sollte.
Die aktuelle Variante gibt die DB-Query zu Debugzwecken nur aus, aber schickt sie nicht ab. Das müsstest du kurz im Code ändern.
PHP-Code:<?php
/**
*
*/
class UploadValidator
{
/** @var string Error message, if any */
protected $message = '';
/** @var array Config values (see constructor) */
protected $config;
/**
*
* @param string $type
* @return boolean
*/
protected function isAllowedMimeType($type)
{
$allowed = false;
foreach ($this->config['allowed_types'] as $entry) {
if ($entry['mime_type'] === $type) {
$allowed = true;
break;
}
}
return $allowed;
}
/**
*
* @param string $type
* @param string $extension
* @return boolean
*/
function isAllowedFileExtension($type, $extension)
{
$allowed = false;
foreach ($this->config['allowed_types'] as $entry) {
if ($entry['mime_type'] === $type) {
if (in_array($extension, $entry['extensions'])) {
$allowed = true;
}
break;
}
}
return $allowed;
}
/**
*
* @param array $config
*/
public function __construct(array $config = array())
{
$defaultConfig = array(
'allowed_types' => array(
array(
'mime_type' => 'image/jpeg',
'extensions' => array('jpg', 'jpeg')
),
array(
'mime_type' => 'image/png',
'extensions' => array('png')
),
array(
'mime_type' => 'image/gif',
'extensions' => array('gif')
)
),
// 20 kB
'maximum_file_size' => 2e4
);
// Override default config values with custom ones
$this->config = array_merge($defaultConfig, $config);
}
/**
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
*
* @param string $tmpFilename
* @param string $originalFilename
* @return boolean
*/
public function isValid($tmpFilename, $originalFilename)
{
$this->message = '';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $tmpFilename);
finfo_close($finfo);
$valid = true;
if ($valid) {
if (!$this->isAllowedMimeType($type)) {
$this->message = 'Unsupported MIME type "' . $type . '"';
$valid = false;
}
}
if ($valid) {
$extension = strtolower(
pathinfo($originalFilename, PATHINFO_EXTENSION));
if (!$this->isAllowedFileExtension($type, $extension)) {
$this->message = 'Unsupported file extension "' . $extension . '" for MIME type "'.$type.'"';
$valid = false;
}
}
if ($valid) {
$fs = filesize($tmpFilename);
if ($fs > $this->config['maximum_file_size']) {
$this->message =
sprintf('File is too big (%s byte). Maximum size is %s byte.',
$fs, $this->config['maximum_file_size']);
$valid = false;
}
}
return $valid;
}
}
/**
*
*/
class DbAdapter
{
protected $link;
public function __construct($server, $username, $password, $database)
{
$this->link = mysql_connect($server, $username, $password);
mysql_select_db($database, $this->link);
}
/**
*
* @param string $tableName
* @param array $data
* @return type
*/
public function insert($tableName, $data)
{
$keys = array_keys($data);
$values = array();
foreach ($keys as $key) {
$values[] = mysql_real_escape_string($data[$key], $this->link);
}
$tpl = "
INSERT INTO
`%s`
(
%s
)
VALUES
(
%s
)
";
$query = sprintf($tpl,
$tableName,
'`' . implode('`, `', $keys) . '`',
"'" . implode("', '", $values) . "'");
var_dump($query);
#$result = mysql_query($query, $this->link);
}
}
// Configuration
$uploadDir = realpath('./tmp');
$db = new DbAdapter('localhost', '', '', 'test');
$uploadAttempt = false;
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['Submit'])) {
$uploadAttempt = true;
try {
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
throw new Exception('Upload failure');
}
$validator = new UploadValidator();
if ($validator->isValid($_FILES['image']['tmp_name'], $_FILES['image']['name'])) {
$newPath = $uploadDir . '/' . $_FILES['image']['name'];
$success = move_uploaded_file($_FILES['image']['tmp_name'], $newPath);
if (!$success) {
throw new Exception('Error moving file');
}
$dbData = array(
'filename' => $_FILES['image']['name'],
'filesize' => filesize($newPath),
'date' => date('Y-m-d H:i:s')
);
$db->insert('upload', $dbData);
} else {
throw new Exception($validator->getMessage());
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
}
?>
<?php if ($uploadAttempt) : ?>
<?php if ($error === '') : ?>
<p>Datei hochgeladen.</p>
<?php else : ?>
<p>Fehler: <?php echo $error; ?></p>
<?php endif; ?>
<?php endif; ?>
<!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image"></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
Aktive Benutzer
Aktive Benutzer
Aktive Benutzer in diesem Thema: 1 (Registrierte Benutzer: 0, Gäste: 1)
Ähnliche Themen
-
URL QueryString akzeptieren ...
Von flyingdutchman im Forum HTML und XHTMLAntworten: 3Letzter Beitrag: 08.09.2011, 17:25 -
Bildergalerie - Akzeptieren Funktion
Von Witschi262 im Forum PHPAntworten: 5Letzter Beitrag: 10.08.2010, 14:43 -
RAR-Datei öffnen, Inhalt mit bestimmten Dateitypen anzeigen.
Von aJunkie im Forum PHPAntworten: 3Letzter Beitrag: 12.04.2010, 12:57 -
Mehr Statistiken ?
Von Niklas im Forum html.de internAntworten: 19Letzter Beitrag: 14.12.2009, 15:06 -
PHP will 2. elseif net akzeptieren
Von matibaski im Forum PHPAntworten: 3Letzter Beitrag: 02.05.2007, 19:46


LinkBack URL
About LinkBacks
Zitieren
Wie funktioniert...
Heute, 16:50 in Datenbanken - z.B. MySQL