UploadedFile.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use yii\base\BaseObject;
  9. use yii\helpers\Html;
  10. /**
  11. * UploadedFile represents the information for an uploaded file.
  12. *
  13. * You can call [[getInstance()]] to retrieve the instance of an uploaded file,
  14. * and then use [[saveAs()]] to save it on the server.
  15. * You may also query other information about the file, including [[name]],
  16. * [[tempName]], [[type]], [[size]] and [[error]].
  17. *
  18. * For more details and usage information on UploadedFile, see the [guide article on handling uploads](guide:input-file-upload).
  19. *
  20. * @property string $baseName Original file base name. This property is read-only.
  21. * @property string $extension File extension. This property is read-only.
  22. * @property bool $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed
  23. * error code information. This property is read-only.
  24. *
  25. * @author Qiang Xue <qiang.xue@gmail.com>
  26. * @since 2.0
  27. */
  28. class UploadedFile extends BaseObject
  29. {
  30. /**
  31. * @var string the original name of the file being uploaded
  32. */
  33. public $name;
  34. /**
  35. * @var string the path of the uploaded file on the server.
  36. * Note, this is a temporary file which will be automatically deleted by PHP
  37. * after the current request is processed.
  38. */
  39. public $tempName;
  40. /**
  41. * @var string the MIME-type of the uploaded file (such as "image/gif").
  42. * Since this MIME type is not checked on the server-side, do not take this value for granted.
  43. * Instead, use [[\yii\helpers\FileHelper::getMimeType()]] to determine the exact MIME type.
  44. */
  45. public $type;
  46. /**
  47. * @var int the actual size of the uploaded file in bytes
  48. */
  49. public $size;
  50. /**
  51. * @var int an error code describing the status of this file uploading.
  52. * @see https://secure.php.net/manual/en/features.file-upload.errors.php
  53. */
  54. public $error;
  55. private static $_files;
  56. /**
  57. * String output.
  58. * This is PHP magic method that returns string representation of an object.
  59. * The implementation here returns the uploaded file's name.
  60. * @return string the string representation of the object
  61. */
  62. public function __toString()
  63. {
  64. return $this->name;
  65. }
  66. /**
  67. * Returns an uploaded file for the given model attribute.
  68. * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]].
  69. * @param \yii\base\Model $model the data model
  70. * @param string $attribute the attribute name. The attribute name may contain array indexes.
  71. * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
  72. * @return null|UploadedFile the instance of the uploaded file.
  73. * Null is returned if no file is uploaded for the specified model attribute.
  74. * @see getInstanceByName()
  75. */
  76. public static function getInstance($model, $attribute)
  77. {
  78. $name = Html::getInputName($model, $attribute);
  79. return static::getInstanceByName($name);
  80. }
  81. /**
  82. * Returns all uploaded files for the given model attribute.
  83. * @param \yii\base\Model $model the data model
  84. * @param string $attribute the attribute name. The attribute name may contain array indexes
  85. * for tabular file uploading, e.g. '[1]file'.
  86. * @return UploadedFile[] array of UploadedFile objects.
  87. * Empty array is returned if no available file was found for the given attribute.
  88. */
  89. public static function getInstances($model, $attribute)
  90. {
  91. $name = Html::getInputName($model, $attribute);
  92. return static::getInstancesByName($name);
  93. }
  94. /**
  95. * Returns an uploaded file according to the given file input name.
  96. * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
  97. * @param string $name the name of the file input field.
  98. * @return null|UploadedFile the instance of the uploaded file.
  99. * Null is returned if no file is uploaded for the specified name.
  100. */
  101. public static function getInstanceByName($name)
  102. {
  103. $files = self::loadFiles();
  104. return isset($files[$name]) ? new static($files[$name]) : null;
  105. }
  106. /**
  107. * Returns an array of uploaded files corresponding to the specified file input name.
  108. * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
  109. * 'files[n]'..., and you can retrieve them all by passing 'files' as the name.
  110. * @param string $name the name of the array of files
  111. * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned
  112. * if no adequate upload was found. Please note that this array will contain
  113. * all files from all sub-arrays regardless how deeply nested they are.
  114. */
  115. public static function getInstancesByName($name)
  116. {
  117. $files = self::loadFiles();
  118. if (isset($files[$name])) {
  119. return [new static($files[$name])];
  120. }
  121. $results = [];
  122. foreach ($files as $key => $file) {
  123. if (strpos($key, "{$name}[") === 0) {
  124. $results[] = new static($file);
  125. }
  126. }
  127. return $results;
  128. }
  129. /**
  130. * Cleans up the loaded UploadedFile instances.
  131. * This method is mainly used by test scripts to set up a fixture.
  132. */
  133. public static function reset()
  134. {
  135. self::$_files = null;
  136. }
  137. /**
  138. * Saves the uploaded file.
  139. * Note that this method uses php's move_uploaded_file() method. If the target file `$file`
  140. * already exists, it will be overwritten.
  141. * @param string $file the file path used to save the uploaded file
  142. * @param bool $deleteTempFile whether to delete the temporary file after saving.
  143. * If true, you will not be able to save the uploaded file again in the current request.
  144. * @return bool true whether the file is saved successfully
  145. * @see error
  146. */
  147. public function saveAs($file, $deleteTempFile = true)
  148. {
  149. if ($this->error == UPLOAD_ERR_OK) {
  150. if ($deleteTempFile) {
  151. return move_uploaded_file($this->tempName, $file);
  152. } elseif (is_uploaded_file($this->tempName)) {
  153. return copy($this->tempName, $file);
  154. }
  155. }
  156. return false;
  157. }
  158. /**
  159. * @return string original file base name
  160. */
  161. public function getBaseName()
  162. {
  163. // https://github.com/yiisoft/yii2/issues/11012
  164. $pathInfo = pathinfo('_' . $this->name, PATHINFO_FILENAME);
  165. return mb_substr($pathInfo, 1, mb_strlen($pathInfo, '8bit'), '8bit');
  166. }
  167. /**
  168. * @return string file extension
  169. */
  170. public function getExtension()
  171. {
  172. return strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
  173. }
  174. /**
  175. * @return bool whether there is an error with the uploaded file.
  176. * Check [[error]] for detailed error code information.
  177. */
  178. public function getHasError()
  179. {
  180. return $this->error != UPLOAD_ERR_OK;
  181. }
  182. /**
  183. * Creates UploadedFile instances from $_FILE.
  184. * @return array the UploadedFile instances
  185. */
  186. private static function loadFiles()
  187. {
  188. if (self::$_files === null) {
  189. self::$_files = [];
  190. if (isset($_FILES) && is_array($_FILES)) {
  191. foreach ($_FILES as $class => $info) {
  192. self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
  193. }
  194. }
  195. }
  196. return self::$_files;
  197. }
  198. /**
  199. * Creates UploadedFile instances from $_FILE recursively.
  200. * @param string $key key for identifying uploaded file: class name and sub-array indexes
  201. * @param mixed $names file names provided by PHP
  202. * @param mixed $tempNames temporary file names provided by PHP
  203. * @param mixed $types file types provided by PHP
  204. * @param mixed $sizes file sizes provided by PHP
  205. * @param mixed $errors uploading issues provided by PHP
  206. */
  207. private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
  208. {
  209. if (is_array($names)) {
  210. foreach ($names as $i => $name) {
  211. self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
  212. }
  213. } elseif ((int) $errors !== UPLOAD_ERR_NO_FILE) {
  214. self::$_files[$key] = [
  215. 'name' => $names,
  216. 'tempName' => $tempNames,
  217. 'type' => $types,
  218. 'size' => $sizes,
  219. 'error' => $errors,
  220. ];
  221. }
  222. }
  223. }