« powrót

Klasa do upload'u pliku na serwer [PHP]

Opublikowano: 2009-11-07 , wyświetlono: 6498

Prosta klasa ułatwiająca upload plików na serwer.


<?php

//=====================================================
//
// (c) ChinaSoft 2009
// Class UploadFile
//
// Example:
//
//  html form:
//  <form name="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
//    File: <input type="file" name="filename" size="100" maxlength="200">
//    <input class="Button" type="submit" name="submit" value="Upload file">
//  </form>
//
//  php code:
//    $upload = new UploadFile("filename");
//    $fname = $upload->Upload("/upload_dir/", "target_filename_without_extension");
//
//=====================================================

class UploadFile
{
  private $parameter;
  private $fileName;
  private $fileExtension;

  // constructor
  function __construct($param)
  {
    $this->parameter = $param;
  }

  public function getFileName()
  {
    return ($this->fileName);
  }

  public function getFileExtension()
  {
    return ($this->fileExtension);
  }
  
  // upload file
  public function Upload($dir, $name)
  {
    if (is_uploaded_file($_FILES[$this->parameter]['tmp_name']))
    {
      $this->fileName = $_FILES[$this->parameter]['name'];
      $this->fileExtension = $this->getExtension($this->fileName);
    
      move_uploaded_file($_FILES[$this->parameter]['tmp_name'], $dir . $name . "." . $this->fileExtension);
    }
    
    return ($name . "." . $this->fileExtension);
  }

  // get extension from name
  private function getExtension($filepath)
  {
    return strtolower(str_replace(".", "", strrchr($filepath, ".")));
  } 
}

?>



Komentarze: