UploadedFile.php 8.7 KB

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