UploadedFile.php 8.9 KB

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