/** * Download file from the link * @param string $url * @param string $path * @param string $name * @param string $extension * @return array|bool * @throws Exception */ public static function saveFromUrl($url, $path, $name = null, $extension = 'png') { if (!FileHelper::createDirectory($path)) { throw new Exception("Directory not created \"{$path}\"."); } $file = file_get_contents(urldecode($url)); $extension = trim($extension, " \t\n\r\v."); if ($name == null) { $name = FileHelper::generateRandomName($path, $extension); } else { $name = $name . '.' . $extension; } if (file_put_contents($path . DIRECTORY_SEPARATOR . $name, $file)) { return ['name' => $name, 'path' => $path]; } return false; }
/** * Сохранение файла на сервере */ public function save() { // Если это действительно экземпляр объекта файла if ($this->file instanceof UploadedFile) { if (!FileHelper::createDirectory($this->_path)) { throw new InvalidParamException("Directory specified in '{$this->_path}' attribute doesn't exist or cannot be created."); } $name = FileHelper::generateRandomName($this->_path, $this->file->getExtension()); $filePath = $this->_path . DIRECTORY_SEPARATOR . $name; // Если оригинальная картинка сохранилась if ($this->file->saveAs($filePath)) { $imageInfo = getimagesize($filePath); list($width, $height) = $imageInfo; $this->_width = $width; $this->_height = $height; $this->_name = $name; /** @var ImagePathMap $imagePathMap */ $imagePathMap = Yii::$app->get('imagePathMap', false); if ($imagePathMap != null) { $imagePathMap->add($this->_name, $this->_pathID); } return true; } } return false; }