Move file from one directory to other directory in yii2 - yii2

I have uploaded file on my shared server now I want to move file using yii2 libraries how can I move this file.

Simple use this:
http://php.net/manual/en/function.rename.php
or in uploadAction you can use saveAs method when you upload file like this:
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
manual:
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

Related

Argument 1 passed to yii\web\User::login() must implement interface yii\web\IdentityInterface

These are my files:
config/web.php
'user' => [
'identityClass' => '\app\models\User',
'enableAutoLogin' => false,
],
SiteController.php
public function actionSignin()
{
$model = new SigninForm();
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
if($model->load(Yii::$app->request->post()) and $model->validate())
{
$identity = User::findOne(['email' => $model->email])
Yii::$app->user->login($identity);
}
return $this->render('signin',compact('model'));
}
User.php
namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
/* and all methods Identityinterface is here!*/
}
I'm getting an error that I'm not using IdentityInterface in my User.php model. Where is my mistake?
You need to define all the methods necessary for Implementing IdentityInterface
as given here, and 2 additional methods that would be used by the login method add them to your class first.
class User extends ActiveRecord implements IdentityInterface
{
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
Then you SigninForm should look like following
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* SigninForm is the model behind the login form.
*
* #property User|null $user This property is read-only.
*
*/
class SigninForm extends Model {
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules() {
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params) {
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return bool whether the user is logged in successfully
*/
public function login() {
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0));
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser() {
if ($this->_user === false) {
$this->_user = User::findOne($this->username);
}
return $this->_user;
}
}
Update your Signup action to the following
public function actionSignin()
{
$model = new SigninForm();
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
if($model->load(Yii::$app->request->post()) && $model->login())
{
return $this->goBack();
}
return $this->render('signin',compact('model'));
}
And then add the following inside your config/web.php under components as it is shown in the following example:
'components'=>[
'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
// 'loginUrl' => ['user/login'],
// ...
]
]
You should look into documentation more thoroughly here is a good video tutorial that would guide you step by step to implement your login interface.
Hope it helps

Yii2 creating simple singleton

I am trying to create simple singleton in yii2 contoller. Maybe i misunderstood something about this pattern but i decide to try. So i have a CRUD. When i got one instance of that class in the db and i decide to update it, the $instance variable is empty(null). Is it because of the page reloading after the creation of the instance and that's why my static variable is set to null again? And is it even possible to make it like this or i am really, really on wrong way? Thank you in advance!
<?php
namespace backend\controllers;
use backend\models\DeliveryTime;
use yii\data\ActiveDataProvider;
use Yii;
class DeliveryTimeController extends \yii\web\Controller
{
public static $instance = null;
public function actionIndex()
{
$delivery = new ActiveDataProvider([
'query' => DeliveryTime::find()->where('id>0')
]);
return $this->render('index', ['delivery' => $delivery]);
}
public static function setInstance()
{
if(self::$instance == null){
self::$instance = new DeliveryTime();
}
return self::$instance;
}
public static function getInstance(){
return self::$instance;
}
public function actionCreate()
{
$delivery = DeliveryTimeController::setInstance();
if($delivery->load(Yii::$app->request->post()) && $delivery->save()){
self::$instance = $delivery;
return $this->redirect(['index']);
}
return $this->render('create', ['model' => $delivery]);
}
public function actionUpdate()
{
$delivery = DeliveryTimeController::getInstance();
if($delivery->load(Yii::$app->request->post()) && $delivery->save()){
return $this->render(['index']);
}
return $this->render('update', ['model' => $delivery]);
}
public function actionDelete(){
$delivery = DeliveryTimeController::getInstance();
if($delivery != null){
$delivery->delete();
return $this->redirect(['index']);
}
}
}
For design patterns i would recommend to check out
https://github.com/kamranahmedse/design-patterns-for-humans
https://github.com/edin/php-design-patterns (my github repo :)
For what you are trying it's better to just create new instance.

Class name dynamically in hasOne not working

public function getResource() {
return $this->hasOne(User::className(), ['id' => 'resource_id']);
}
this function working fine but when i use this
public function getResource() {
$model = ucfirst($this->resource_type);
return $this->hasOne($model::className(), ['id' => 'resource_id']);
}
its give me error "Class 'User' not found".
Thanks
you have to use the name including namespace if you specify it dynamically.
public function getResource() {
$model = "api\\models\\".ucfirst($this->resource_type);
return $this->hasOne($model::className(), ['id' => 'resource_id']);
}

Upload the file to a folder and saving the name to the database in yii2

Good afternoon!
There is a question about the file upload to yii2. There are two folders in it that will store the original and thumbnail image. At me files are loaded but here the name of a file does not load in a database
Model
namespace app\models;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;
use yii\imagine\Image;
use Imagine\Image\Box;
/**
* This is the model class for table "images".
*
* #property integer $id
* #property string $original_image
* #property string $prev_image
*/
class Images extends ActiveRecord
{
public $imageFile;
public $file_name;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'images';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['prev_image'], 'string', 'max' => 255],
[['original_image'], 'string'],
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxSize' => 1024 * 1024 * 7],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'original_image' => 'Original Image',
'prev_image' => 'Prev Image',
];
}
public function upload()
{
$temp=substr(md5(microtime() . rand(0, 9999)), 0, 20);
if ($this->validate()) {
$this->imageFile->saveAs('uploads/original/'.$temp.$this->imageFile->baseName . '.' . $this->imageFile->extension);
$imagine = Image::getImagine();
$image = $imagine->open('uploads/original/' . $temp.$this->imageFile);
$image->resize(new Box(250, 150))->save('uploads/prev/' . $temp.$this
->imageFile->baseName . '.' . $this->imageFile->extension, ['quality' => 70]);
$this->file_name=$temp.$this->imageFile->baseName . '.' . $this->imageFile->extension;
return true;
} else {
return false;
}
}
}
Controller
namespace app\controllers;
use app\models\Images;
use Yii;
use yii\web\UploadedFile;
class ImageController extends \yii\web\Controller
{
public function actionUpload()
{
$model = new Images();
if ($model->load(Yii::$app->request->post())) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->prev_image=$model->file_name;
$model->original_image=$model->file_name;
$model->save();
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
A question how to save a file name in database? Thank you in advance
It's because save happens before uplaod action, but you only define file_name in upload function. Save is what saves it in to the database.
Controller should look like this:
namespace app\controllers;
use app\models\Images;
use Yii;
use yii\web\UploadedFile;
class ImageController extends \yii\web\Controller
{
public function actionUpload(){
$model = new Images();
if ($model->load(Yii::$app->request->post())) {
$uploadedFile = UploadedFile::getInstance($model, 'imageFile');
$model->imageFile = $uploadedFile;
$model->prev_image = $uploadedFile->name
$model->original_image = $uploadedFile->name
$model->save();
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}

Yii::$app->user->isGuest always true on main.php after login

I want to implement user login into yii2 basic app.everything works properly except, when I tries to access Yii::$app->user->isGuest on layout main page. it always returns true. whats going wrong here?, please help me
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
Yii::$app->user->isGuest; // i m getting this as false, which is correct, but after goBack(), I m getting it as true
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
Login Mehod from LoginForm.php
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
Note : I am using custom theme, which rests outside the web folder and inside project/themes/ directory
** User Model is as follows**
<?php
namespace app\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\web\NotFoundHttpException;
class User extends ActiveRecord implements IdentityInterface {
private $id;
private $authKey;
const STATUS_DELETED = '0';
const STATUS_ACTIVE = '10';
public static function tableName() {
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
public static function findByEmail($email) {
$user_type = ['U'];
return static::find()
->andWhere('email = :email', [':email' => $email])
->andFilterWhere(['in', 'user_type', $user_type])
->one();
}
public static function findIdentity($id) {
$user = static::find()->where(['id' => $id, 'status' => self::STATUS_ACTIVE,])->one();
if (empty($user->id)) {
\Yii::$app->session->destroy();
}
return $user;
}
public static function findIdentityByAccessToken($token, $type = null) {
$user = static::find()
->where([
'access_token' => $token,
'status' => self::STATUS_ACTIVE,
])
->one();
if (!empty($user)) {
return $user;
} else {
throw new NotFoundHttpException('Invalid access token.');
}
}
}
Remove the lines:
private $id;
private $authKey;
from User class.
You should not directly declare ActiveRecord attributes that come from database as stated in the Guide.
Note: The Active Record attributes are named after the associated table columns in a case-sensitive manner. Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.