UploadedFile.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\File;
  11. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
  13. use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
  14. /**
  15. * A file uploaded through a form.
  16. *
  17. * @author Bernhard Schussek <bschussek@gmail.com>
  18. * @author Florian Eckerstorfer <florian@eckerstorfer.org>
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @api
  22. */
  23. class UploadedFile extends File
  24. {
  25. /**
  26. * Whether the test mode is activated.
  27. *
  28. * Local files are used in test mode hence the code should not enforce HTTP uploads.
  29. *
  30. * @var Boolean
  31. */
  32. private $test = false;
  33. /**
  34. * The original name of the uploaded file.
  35. *
  36. * @var string
  37. */
  38. private $originalName;
  39. /**
  40. * The mime type provided by the uploader.
  41. *
  42. * @var string
  43. */
  44. private $mimeType;
  45. /**
  46. * The file size provided by the uploader.
  47. *
  48. * @var string
  49. */
  50. private $size;
  51. /**
  52. * The UPLOAD_ERR_XXX constant provided by the uploader.
  53. *
  54. * @var integer
  55. */
  56. private $error;
  57. /**
  58. * Accepts the information of the uploaded file as provided by the PHP global $_FILES.
  59. *
  60. * The file object is only created when the uploaded file is valid (i.e. when the
  61. * isValid() method returns true). Otherwise the only methods that could be called
  62. * on an UploadedFile instance are:
  63. *
  64. * * getClientOriginalName,
  65. * * getClientMimeType,
  66. * * isValid,
  67. * * getError.
  68. *
  69. * Calling any other method on an non-valid instance will cause an unpredictable result.
  70. *
  71. * @param string $path The full temporary path to the file
  72. * @param string $originalName The original file name
  73. * @param string $mimeType The type of the file as provided by PHP
  74. * @param integer $size The file size
  75. * @param integer $error The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants)
  76. * @param Boolean $test Whether the test mode is active
  77. *
  78. * @throws FileException If file_uploads is disabled
  79. * @throws FileNotFoundException If the file does not exist
  80. *
  81. * @api
  82. */
  83. public function __construct($path, $originalName, $mimeType = null, $size = null, $error = null, $test = false)
  84. {
  85. if (!ini_get('file_uploads')) {
  86. throw new FileException(sprintf('Unable to create UploadedFile because "file_uploads" is disabled in your php.ini file (%s)', get_cfg_var('cfg_file_path')));
  87. }
  88. $this->originalName = $this->getName($originalName);
  89. $this->mimeType = $mimeType ?: 'application/octet-stream';
  90. $this->size = $size;
  91. $this->error = $error ?: UPLOAD_ERR_OK;
  92. $this->test = (Boolean) $test;
  93. parent::__construct($path, UPLOAD_ERR_OK === $this->error);
  94. }
  95. /**
  96. * Returns the original file name.
  97. *
  98. * It is extracted from the request from which the file has been uploaded.
  99. * Then is should not be considered as a safe value.
  100. *
  101. * @return string|null The original name
  102. *
  103. * @api
  104. */
  105. public function getClientOriginalName()
  106. {
  107. return $this->originalName;
  108. }
  109. /**
  110. * Returns the original file extension
  111. *
  112. * It is extracted from the original file name that was uploaded.
  113. * Then is should not be considered as a safe value.
  114. *
  115. * @return string The extension
  116. */
  117. public function getClientOriginalExtension()
  118. {
  119. return pathinfo($this->originalName, PATHINFO_EXTENSION);
  120. }
  121. /**
  122. * Returns the file mime type.
  123. *
  124. * The client mime type is extracted from the request from which the file
  125. * was uploaded, so it should not be considered as a safe value.
  126. *
  127. * For a trusted mime type, use getMimeType() instead (which guesses the mime
  128. * type based on the file content).
  129. *
  130. * @return string|null The mime type
  131. *
  132. * @see getMimeType
  133. *
  134. * @api
  135. */
  136. public function getClientMimeType()
  137. {
  138. return $this->mimeType;
  139. }
  140. /**
  141. * Returns the extension based on the client mime type.
  142. *
  143. * If the mime type is unknown, returns null.
  144. *
  145. * This method uses the mime type as guessed by getClientMimeType()
  146. * to guess the file extension. As such, the extension returned
  147. * by this method cannot be trusted.
  148. *
  149. * For a trusted extension, use guessExtension() instead (which guesses
  150. * the extension based on the guessed mime type for the file).
  151. *
  152. * @return string|null The guessed extension or null if it cannot be guessed
  153. *
  154. * @see guessExtension()
  155. * @see getClientMimeType()
  156. */
  157. public function guessClientExtension()
  158. {
  159. $type = $this->getClientMimeType();
  160. $guesser = ExtensionGuesser::getInstance();
  161. return $guesser->guess($type);
  162. }
  163. /**
  164. * Returns the file size.
  165. *
  166. * It is extracted from the request from which the file has been uploaded.
  167. * Then is should not be considered as a safe value.
  168. *
  169. * @return integer|null The file size
  170. *
  171. * @api
  172. */
  173. public function getClientSize()
  174. {
  175. return $this->size;
  176. }
  177. /**
  178. * Returns the upload error.
  179. *
  180. * If the upload was successful, the constant UPLOAD_ERR_OK is returned.
  181. * Otherwise one of the other UPLOAD_ERR_XXX constants is returned.
  182. *
  183. * @return integer The upload error
  184. *
  185. * @api
  186. */
  187. public function getError()
  188. {
  189. return $this->error;
  190. }
  191. /**
  192. * Returns whether the file was uploaded successfully.
  193. *
  194. * @return Boolean True if the file has been uploaded with HTTP and no error occurred.
  195. *
  196. * @api
  197. */
  198. public function isValid()
  199. {
  200. $isOk = $this->error === UPLOAD_ERR_OK;
  201. return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
  202. }
  203. /**
  204. * Moves the file to a new location.
  205. *
  206. * @param string $directory The destination folder
  207. * @param string $name The new file name
  208. *
  209. * @return File A File object representing the new file
  210. *
  211. * @throws FileException if, for any reason, the file could not have been moved
  212. *
  213. * @api
  214. */
  215. public function move($directory, $name = null)
  216. {
  217. if ($this->isValid()) {
  218. if ($this->test) {
  219. return parent::move($directory, $name);
  220. }
  221. $target = $this->getTargetFile($directory, $name);
  222. if (!@move_uploaded_file($this->getPathname(), $target)) {
  223. $error = error_get_last();
  224. throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
  225. }
  226. @chmod($target, 0666 & ~umask());
  227. return $target;
  228. }
  229. throw new FileException($this->getErrorMessage($this->getError()));
  230. }
  231. /**
  232. * Returns the maximum size of an uploaded file as configured in php.ini
  233. *
  234. * @return int The maximum size of an uploaded file in bytes
  235. */
  236. public static function getMaxFilesize()
  237. {
  238. $max = strtolower(ini_get('upload_max_filesize'));
  239. if ('' === $max) {
  240. return PHP_INT_MAX;
  241. }
  242. if (preg_match('#^\+?(0x?)?(.*?)([kmg]?)$#', $max, $match)) {
  243. $shifts = array('' => 0, 'k' => 10, 'm' => 20, 'g' => 30);
  244. $bases = array('' => 10, '0' => 8, '0x' => 16);
  245. return intval($match[2], $bases[$match[1]]) << $shifts[$match[3]];
  246. }
  247. return 0;
  248. }
  249. /**
  250. * Returns an informative upload error message.
  251. *
  252. * @param int $code The error code returned by an upload attempt
  253. *
  254. * @return string The error message regarding the specified error code
  255. */
  256. private function getErrorMessage($errorCode)
  257. {
  258. static $errors = array(
  259. UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).',
  260. UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
  261. UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
  262. UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
  263. UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
  264. UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
  265. UPLOAD_ERR_EXTENSION => 'File upload was stopped by a php extension.',
  266. );
  267. $maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0;
  268. $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.';
  269. return sprintf($message, $this->getClientOriginalName(), $maxFilesize);
  270. }
  271. }