Форма загрузки PHP с несколькими расширениями файлов и заглавными буквами - PullRequest
2 голосов
/ 12 января 2011

Я получил свою форму загрузки php (с разрешением .jpg), но не уверен, как добавить .JPG (заглавные буквы) или .jpeg.

Может кто-нибудь показать мне, как добавить эти расширения в следующий код?

<?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"] < 16000000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/upload/'.$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!";
        } 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 15 Mb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

Большое спасибо за вашу помощь и время!

Ответы [ 4 ]

2 голосов
/ 12 января 2011

В дополнение к @Swanny у вас есть несколько дополнительных опций:

Подход in_array (в сочетании с strtolower ):

if (in_array(strtolower($est),Array('jpg','jpeg')))

Используется strcasecmp для исключения регистра:

if (strcasecmp($ext,'jpg') === 0 || strcasecmp($ext,'jpeg') === 0)

Или, хорошо отрекомендовавший себя метод RegEx (который исключил создание переменной $ext:

if (preg_match('/\.(jpe?g)$/i',$filename))

, которая также может быть изменена следующим образом (добавление дополнительных расширений, разделенных символом (|))

if (preg_match('/\.(jpe?g|gif|png)$/i',$filename))
1 голос
/ 12 января 2011

Преобразование расширения в нижний регистр при сравнении.

$ext = strtolower($ext);

if ( ($ext == 'jpg' || $ext == 'jpeg') && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_file"]["size"] < 16000000)) {
1 голос
/ 12 января 2011

Возможно, вы измените строку 6 с:

if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&

до:

if (($ext == "jpg" || $ext == "jpeg" || $ext == "JPG") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&

Хотя, если вы хотите расширить это, я бы порекомендовал использовать массив типов файлов и проверить массив, гораздо проще управлять. В частности, используя функцию in_array http://php.net/manual/en/function.in-array.php

0 голосов
/ 12 января 2011

Попробуй это.Преобразует расширение текущего файла в нижний регистр, используя strtolower (), затем проверяет массив принятых расширений, используя in_array ():

<?php
$acceptedExts = array ('jpg','jpeg');

//–check 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 = strtolower (substr($filename, strrpos($filename, '.') + 1));
  if (in_array($ext,$acceptedExts) && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_file"]["size"] < 16000000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/upload/'.$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!";
        } 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 15 Mb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

Обратите внимание, что оно не будет работать для других типов изображений, как вывсе еще проверяю тип файла image / jpeg:

$_FILES["uploaded_file"]["type"] == "image/jpeg"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...