UploadedFile.php 10.0 KB

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