FileUpload.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /** @package verysimple::HTTP */
  3. /**
  4. * Encapsulates a file upload.
  5. *
  6. * Utility class for dealing with file uploads and converting them into
  7. * a string that is easily insertable into a database
  8. *
  9. * @package verysimple::HTTP
  10. * @author VerySimple Inc.
  11. * @copyright 1997-2007 VerySimple, Inc. http://www.verysimple.com
  12. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  13. * @version 1.0
  14. */
  15. class FileUpload
  16. {
  17. public $Name;
  18. public $Size;
  19. public $Type;
  20. public $Extension;
  21. public $Data;
  22. /**
  23. * Returns a file upload as xml that is ready to save to a file or database
  24. *
  25. * @param string $fieldname
  26. * @return string
  27. */
  28. public function ToXML($base64 = true)
  29. {
  30. return "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"
  31. . "<file>\r\n"
  32. . "<name>".$this->Name."</name>\r\n"
  33. . "<size>".$this->Size."</size>\r\n"
  34. . "<type>".$this->Type."</type>\r\n"
  35. . "<Extension>".$this->Extension."</Extension>\r\n"
  36. . "<encoding>" . ($base64 ? "base64" : "none") . "</encoding>\r\n"
  37. . "<data>" . ($base64 ? base64_encode($this->Data) : $this->Data) . "</data>\r\n"
  38. . "</file>";
  39. }
  40. /**
  41. * Loads this FileUpload object from previously obtained from ToXML()
  42. *
  43. * @param string $xml
  44. */
  45. public function FromXML($xml)
  46. {
  47. $sxo = new SimpleXMLElement($xml);
  48. if($sxo->encoding == "base64")
  49. {
  50. $this->Data = base64_decode($sxo->data);
  51. }
  52. else
  53. {
  54. $this->Data = $sxo->data;
  55. }
  56. $this->Name = $attachment->name;
  57. $this->Type = $attachment->type;
  58. $this->Size = $attachment->size;
  59. $this->Extension = $attachment->extension;
  60. }
  61. /**
  62. * Saves the file upload to the given path
  63. * @param string $path full path to save directory (trailing slash required)
  64. * @param string $alternate_name (optional) if not provided, $this->Name is used
  65. * @param bool $chmod (default=true) set file permission to 666
  66. */
  67. public function SaveTo($path, $alternate_name="", $chmod=true)
  68. {
  69. $name = $alternate_name ? $alternate_name : $this->Name;
  70. $fullpath = $path . $name;
  71. $handle = fopen($fullpath, "w");
  72. fwrite($handle, $this->Data);
  73. fclose($handle);
  74. if ($chmod) @chmod($fullpath, 0666);
  75. }
  76. }
  77. ?>