UploadedFile.php 10KB

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