Просмотр поста

.
Delphinum

Мне кажется загрузку файла на сервер у вас можно ограничить одним классом вида:

HTML форма (+/-)
<form method="POST" action="/index.php" enctype="multipart/form-data">
<input type="file" name="first"/>
<input type="file" name="second"/>
<input type="file" name="last"/>
<input type="submit"/>
</form>


Класс (+/-)
class UploadedFile{
  /**
   * @var string Адрес файла.
   */
  private $file;

  /**
   * @var int Размер файла.
   */
  private $size;

  /**
   * @var int Код ошибки.
   */
  private $errorStatus;

  /**
   * @var string Имя файла на машине клиента.
   */
  private $clientFilename;

  /**
   * @var string Mime-тип файла на машине клиента.
   */
  private $clientMediaType;

  public function __construct($file, $size, $errorStatus, $clientFilename = null, $clientMediaType = null){
    $this->file = $file;
    $this->size = $size;
    $this->errorStatus = $errorStatus;
    $this->clientFilename = $clientFilename;
    $this->clientMediaType = $clientMediaType;
  }

  // Factories
  /**
   * @param string $name Имя элемента массива $_FILES, в котором содержится 
   * данные целевого файла.
   * 
   * @return self Загружаемый файл.
   */
  public static function createByGlobal($name){
    $file = $_FILES[$name];
    return new static($file['tmp_name'], $file['size'], $file['error'], $file['name'], $file['type']);
  }

  // Getters and Setters
  public function getFile(){
    return $this->file;
  }

  public function getSize(){
    return $this->size;
  }

  public function getErrorStatus(){
    return $this->errorStatus;
  }

  public function getClientFilename(){
    return $this->clientFilename;
  }

  public function getClientMediaType(){
    return $this->clientMediaType;
  }

  // Other
  /**
   * @param string $targetPath Новый адрес, по которому будет перемещен файл.
   *
   * @throws RuntimeException Выбрасывается в случае ошибки при переносе файла.
   */
  public function moveTo($targetPath){
    if(move_uploaded_file($this->file, $targetPath) === false){
      throw new RuntimeException('Error occurred while moving uploaded file');
    }
    $this->file = $targetPath;
  }
}

$file = UploadedFile::createByGlobal('first');
$file->moveTo('file_storage/' . $file->getClientFilename());