UploadedFile.php 10 KB

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