• Jetzt anmelden. Es dauert nur 2 Minuten und ist kostenlos!

Mehr Dateitypen akzeptieren ... ?

maria1

Mitglied
Hallo,

Ich will mein Script so erweitern das alle Bilder-Dateitypen akzeptiert werden sprich PNG,JPEG,GIF,ICO,usw.

Hier das Script:
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";
}
?>

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)) 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";
}
?>

Fehler : Parse error: syntax error, unexpected T_LOGICAL_OR in /home/username/public_html/upload.php on line 8

Danke
 
Werbung:
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:

PHP:
$allowed = array(
    array(
        'extensions' => array('jpeg', 'jpg'),
        'mime'       => 'image/jpeg'
    ),
    array(
        'extensions' => array('png'),
        'mime'       => 'image/png'
    )
    // usw.
);

1. Bestimme MIME-Typ von Upload-Datei.
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.
 
Zuletzt bearbeitet:
Code:
[LEFT][COLOR=#0000BB][FONT=Consolas]<?php
$extension [/FONT][/COLOR][COLOR=#007700][FONT=Consolas]= array([/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"PNG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas], [/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"JPEG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas], [/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"JPG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas], [/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"GIF"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas]);
if ([/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]in_array[/FONT][/COLOR][COLOR=#007700][FONT=Consolas]([/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"PNG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas], [/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]$[/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]extension[/FONT][/COLOR][COLOR=#007700][FONT=Consolas])) {
    echo [/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"Ist PNG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas];
}
if ([/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]in_array[/FONT][/COLOR][COLOR=#007700][FONT=Consolas]([/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"JPG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas], [/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]$[/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]extension[/FONT][/COLOR][COLOR=#007700][FONT=Consolas])) {
    echo [/FONT][/COLOR][COLOR=#DD0000][FONT=Consolas]"Ist JPG"[/FONT][/COLOR][COLOR=#007700][FONT=Consolas];
}
[/FONT][/COLOR][COLOR=#0000BB][FONT=Consolas]?>

[/FONT][/COLOR][/LEFT]
Hast du das so gemeint ? Und jetzt immer so weiter mit allen Image-Endungen oder ?
 
Werbung:
Kannst es posten, wenn du willst. Es war gestern etwas spät, als ich antwortete. Außerdem fiel mir während des Schreibens die Sache mit den Zuordnungen auf, die komplizierter sein kann.
 
Gut ich poste es mal da ich deinen Rat sehr schätze

index.php
Code:
<?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>

write_database.php
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)."')");


	  }
  }


?>

Noch ne Frage, was würdest du für werte abspeichern ?
Ich benötige die id,name,filesize,extension,date hab ich was vergessen was ich später noch brauchen könnte ?

Danke
 
Werbung:
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:
<?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>
 
Zurück
Oben