registration form using Yii framework - yii

I am new to Yii framework. I want to implement a registration form with Yii .
I check the blog project on its demo projects but it hasn't got a registration form.
Do anyone knows a tutorial about this issue?

For registration system.
You should follow the steps.
1st you make a table user/signup/register as you wish.
Now create CRUD for that so you can easily insert your data in user table.
I have a table and it have five different fields i.e. id, name, conatct_no, email, password
Now you create a folder in view named it "register".
In view you just made a file index.php and register.php
register.php is your form. which you can made.
Register.php
<h2>Registration Form</h2>
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'Name'); ?>
<?php echo CHtml::activeTextField($model,'name') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Contact Number'); ?>
<?php echo CHtml::activeTextField($model,'contact_no') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'email'); ?>
<?php echo CHtml::activeTextField($model,'email') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Retype Password'); ?>
<?php echo CHtml::activePasswordField($model,'retypepassword') ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Register'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
Now you need a controller file for registration i.e. registerController.php.
registerController.php
class registerController extends Controller
{
public function actionIndex() {
$this->render('index');
}
public function actionRegister() {
$model = new RegisterForm ;
$newUser = new User;
if(isset($_POST['RegisterForm'])) {
$model->attributes = $_POST['RegisterForm'];
if($model->validate()) {
$newUser->name = $model->name ;
$newUser->contact_no = $model->contact_no;
$newUser->email = $model->email;
$newUser->password = $model->password;
if($newUser->save()) {
$this->_identity = new UserIdentity($newUser->email,$newUser->password);
if($this->_identity->authenticate())
Yii::app()->user->login($this->_identity);
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
$this->render('register',array('model'=>$model));
}
}
Now you need a model file for your validation. RegisterForm.php
class RegisterForm extends CFormModel
{
public $contact_no ;
public $name ;
public $email;
public $password ;
public $retypepassword;
public function tableName()
{
return 'user';
}
public function rules() {
return array(
array('name, contact_no, email, password, retypepassword', 'required'),
array('name, email, password, retypepassword', 'length', 'max'=>200),
array('email', 'email', 'message'=>'Please insert valid Email'),
array('contact_no', 'length', 'max'=>30),
array('retypepassword', 'required', 'on'=>'Register'),
array('password', 'compare', 'compareAttribute'=>'retypepassword'),
array('id, name, contact_no, email', 'safe', 'on'=>'search'),
);
}
}
You need to also change the UserIdentity.php file in your protected/component directory.
class UserIdentity extends CUserIdentity
{
private $_id ;
public function authenticate()
{
$email = strtolower($this->username);
$user = User::model()->find('LOWER(email)=?',array($email));
if($user === null)
$this->errorCode = self::ERROR_USERNAME_INVALID ;
else if(!$user->password === $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID ;
else {
$this->_id = $user->id ;
$this->username = $user->email ;
$this->errorCode = self::ERROR_NONE ;
}
return $this->errorCode == self::ERROR_NONE ;
return !$this->errorCode;
}
public function getId() {
return $this->_id ;
}
}
That's it.
It is a complete registration form set up, i have made it myself.
If you are first timer, then you need to understand how the controller work and how controller interact with view and model. If you are already familiar with it then you may easily can make registration system with your own.
Here is the link which help you to understand yii.
http://www.yiiframework.com/screencasts/
Thanks.

First, create a table for Users. Generate a User model and a controller based on this table using gii and adjust the code to your liking. Inside the User controller create a function to handle the registration:
function actionRegister() {
$model = new User('register');
// collect user input data
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
// validate user input and redirect to the previous page if valid
$model->setAttributes(array(
'datereg' => time(), //additional data you want to insert
'lastlogin' => time() //additional
));
if($model->save())
{
//optional
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
}
}
else
// display the registration form
$this->render('register',array('model'=>$model));
}
You must have a valid view file (register.php)
$login=new LoginForm;
$login->username = $_POST['User']['username'];
$login->password = $_POST['User']['password'];
if($login->validate() && $login->login())
$this->redirect('/pages/welcome');
This block of code 'authenticates' the user and logs him in right after a successful registration. It uses CUserIdentity. $login->login() hashes the password.
Also, you must have something like this to process the data before it inserts it into the table
public function beforeSave() {
if(parent::beforeSave() && $this->isNewRecord) {
$this->password = md5($this->password);
}
return true;
}
Hashing the password inside the controller is also fine. However I wanna do everything DB related inside the Model class.
You may notice that I didn't call $model-validate() here. This is because $model->save() also calls the validation method. More info: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

It is easy to create a form with yii using CActiveForm.
Here is a link of yii documentation :: Yii CActiveForm

You must create Registration form, using CAvtiveForm (see LoginForm for example).
Create your Users model.
Create controller:
class UsersController extends Controller
{
public function actionSignup()
{
$model = new RegistrationForm;
if (isset($_POST['RegistrationForm'])) {
if ($model->validate()) {
$user = new Users;
$user->populateRecord($form->attributes);
$user->save();
$this->redirect(Yii::app()->createUrl('/'));
}
}
$this->render('signup', array('model' => $model));
}
}

Related

Invalid username or password at login() using BlowfishPasswordHasher in CakePHP 2.x

I'm using CakePHP 2.7.8 to build an admin panel. My project contains multiple admins instead of users. That's why I have an admins table in the database and not an users table.
I'm using BlowfishHasher for hashing passwords, and it's working fine. Passwords are hashed before saving to database.
But login() returns:
Invalid username or password, try again
Table admins:
CREATE TABLE `admins` (
`id` char(36) NOT NULL,
`username` varchar(50) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`gender` varchar(45) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`))
Admins model : Admin.php
<?php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher','Controller/Component/Auth');
/**
* Admin Model
*
*/
class Admin extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'first_name';
public function beforeSave($options = array()) {
if(isset($this->data[$this->alias]['password'])){
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
Admins Controller : AdminsController.php
<?php
App::uses('AppController', 'Controller');
/**
* Admins Controller
*
* #property Admin $Admin
* #property PaginatorComponent $Paginator
* #property FlashComponent $Flash
* #property SessionComponent $Session
*/
class AdminsController extends AppController {
/**
* Components
*
* #var array
*/
public $components = array('Paginator', 'Flash', 'Session');
/**
* index method
*
* #return void
*/
public function index() {
$this->Admin->recursive = 0;
$this->set('admins', $this->Paginator->paginate());
}
/**
* login function
*/
public function login(){
if($this->request->is('post')) {
if($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
/**
* logout function
*/
public function logout(){
return $this->redirect($this->Auth->logout());
}
}
App Controller : AppController.php
<?php
App::uses('Controller', 'Controller');
/**
* #package app.Controller
* #link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
public $components = array(
'Flash',
'Auth' => array(
'loginRedirect'=>array(
'controller'=>'admins',
'action'=>'index'
),
'logoutRedirect'=>array(
'controller'=>'admins',
'action'=>'login'
),
'authenticate'=>array(
'Form'=>array(
'passwordHasher'=>'Blowfish'
)
)
)
);
function beforeFilter() {
$this->Auth->authenticate = array(
AuthComponent::ALL => array(
'userModel' => 'Admin'
)
);
$this->Auth->allow('login','add','index');
}
}
Login view : login.ctp
<div class="users form">
<?php echo $this->Flash->render('auth'); ?>
<?php echo $this->Form->create('admin'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
From the problem you've posted, I think there's a chance that your password isn't hashing properly when you're logging in.
Try a bit of debugging in your login action:
public function login(){
if($this->request->is('post')) {
App::uses('BlowfishPasswordHasher','Controller/Component/Auth');
$passwordHasher = new BlowfishPasswordHasher();
$this->request->data['Admin']['password'] = $passwordHasher->hash(
$this->request->data['Admin']['password']
);
pr($this->request->data);
exit;
// Take a look at this $this->request->data["Admin"]["password"] field and compare it with the password you have in the database. Do they match?
if($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
Peace! xD
Try changing your password field from VARCHAR(255) to BINARY(60).
Remember to clear your models cache after doing so.
See the following question for further details:
What column type/length should I use for storing a Bcrypt hashed password in a Database?
Edit
Also the AuthComponent configuration defined in the $components array is being overwritten in beforeFilter().
Try replacing the following code:
$this->Auth->authenticate = array(
AuthComponent::ALL => array(
'userModel' => 'Admin'
)
);
with:
$this->Auth->authenticate[AuthComponent::ALL] = array(
'userModel' => 'Admin'
);
Edit 2
In your view, you have to replace
<?php echo $this->Form->create('admin'); ?>
with
<?php echo $this->Form->create('Admin'); ?>
Case is important.

Save data in a model from a different view

I have two tables, business and review business, in review business I have user_id, business_id,rating and review field. I want to write a review, for that purpose, I need rating and review fields from the review business table, and I want to show them in a view of business which I called (user_business.php). I successfully bring the rating and review field from the review_business table, and user is able to give his review, but the thing is the data is not saving in the review business model. I am posting my code, please find the error.
This is my business controller.
<?php
class BusinessController extends RController
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/admin';
/**
* #return array action filters
*/
public function filters()
{
return array(
// 'accessControl', // perform access control for CRUD operations
// 'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function actionUserbusiness($id) // this is userbusiness
{
//render main layout
$this->layout='main';
$model2 = new ReviewBusiness(); getting fields of review business
$this->render('userbusiness',array(
'model'=>$this->loadModel($id),
'reviewmodel'=>$model2
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Business;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$rnd = rand(0, 9999); // generate random number between 0-9999
$model->attributes = $_POST['Business'];
$uploadedFile = CUploadedFile::getInstance($model, 'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
//$model->attributes=$_POST['Business'];
$_POST['Business']['image'] = $model->image;
$model->attributes=$_POST['Business'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
if($model->save())
{ if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$model->image);
}
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Business');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Business('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Business']))
$model->attributes=$_GET['Business'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Business the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Business::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Business $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='business-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Now view of userbusiness is given below. Oh and I am using dzraty extension for rating.
<?php $form=$this->beginWidget('bootstrap.widgets.BsActiveForm', array(
'id'=>'review-business-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<?php
$this->widget('ext.DzRaty.DzRaty', array(
'model' => $reviewmodel,
'attribute' => 'rating',
)); ?>
</ul>
</div>
<div class="form-group">
<label>Review Text</label>
<?php echo $form->textarea($reviewmodel,'review',array('maxlength'=>500)); ?>
</div>
<?php echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY)); ?>
<?php $this->endWidget(); ?>

Inserting correctly into database pdo

I am having issues getting the SteamID and vac added to the database everything else is working just can not get these two. Here is my code. The connection information to the database is within the config.php I am not having any problems connecting just inserting correctly. Matter if fact it does not insert at all right now.
<?php
require 'config/config.php';
class SteamProfile{
const STEAMAPI_URL_MASK = 'http://steamcommunity.com/profiles/%s/?xml=1';
const UNKONWN_NAME_MASK = 'User #%s (Username Not Found)';
private $steamId;
private $xml;
public function __construct($steamId){
$this->steamId = $steamId;
}
public function getUsername(){
$xml = $this->getXml($this->steamId);
return $xml->steamID ? (string)$xml->steamID : sprintf(self::UNKONWN_NAME_MASK, $this->steamId);
}
private function getXml($steamId){
if ($this->xml){
return $this->xml;
}
$url = sprintf(self::STEAMAPI_URL_MASK, $steamId);
if (!$xml = simplexml_load_file($url)){
throw new UnexpectedValueException(sprintf('Unable to load XML from "%s"', $url));
}
return $this->xml = $xml;
}
public function getVAC(){
$xml = $this->getXml($this->steamId);
return $xml->vacBanned;
}
public function __toString(){
return sprintf("%s (SteamID: %s)", $this->getUsername(), $this->steamId);
}
}
if (empty($_POST)){
?>
<form name="banlist" action="index.php" method="POST">
<label for "SteamID">Steam64ID: </label><input type="text" name="SteamID"/><br />
<label for "bandate">Ban Until: </label><input type="text" name="bandate"/><br />
<button type="submit">Submit</button>
</form>
<?php
}
else{
$form = $_POST;
$SteamID = $form['SteamID'];
$profile = new SteamProfile($SteamID);
$namecheck = $profile->getUsername();
$vac = $profile->getVAC();
$bandate = $form['bandate'];
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname;",$username,$password);
$sql = "INSERT INTO PlayerBans (SteamID, playername, vac, bandate)VALUES(:SteamID, :namecheck, :vac, :bandate)";
$query = $dbh->prepare($sql);
$result = $query->execute(array(':SteamID'=>$SteamID, ':namecheck'=>$namecheck, ':vac'=>$vac, ':bandate'=>$bandate));
if ($result){
echo "Thanks for showing us this ban!";
} else {
echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
}
}
?>
I have no idea what is going wrong as I am not uses to trying to use PDO

simple oophp function not working

I'm new to oop and MVC and I'm trying to test the flow between my index, controller, and model files. All of the test functions work except for 'check status'. What's the problem? The function is highlighted in BOLD. (INDEX)
$Controller = new Controller;
$Controller->ShowRegisterLogin();
?> (CONTROLLER)
Class Controller {
function ShowRegisterLogin() {
echo 'ShowRegisterLogin Function works';
$Model = new Model;
$Model->TestModel();
**$Model->checkStatus();**
}
}
?>
(MODEL)
class Model {
Var $Status = 'return works';
function TestModel() {
echo 'Test Model Works';
}
**function checkStatus() {
return $this->Status;
}**
}
?>
You need to echo the value if you want to see it
echo $Model->checkStatus();
Otherwise, nothing gets done with the return value and it disappears.

Return value from external action in Yii

How to pass a value from external action in Yii to it's parent controller?
for example:
External action looks like:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
.....
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // this line does not work!!
}
}
when I try to get the value of images in the parent controller, nothing return!! Any help I will appreciate.
Update:
I am using an extension to upload a file .. eajaxupload .
There is a long form.. have many fields, one of them is image. I want to upload that image by Ajax before submiting the whole form. Of course after user click on create button.. the controller must take all fields plus image name to store in the db.
The view ..
<div class="elem">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password1'); ?>
<?php echo $form->passwordField($model,'password1',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password1'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'password2'); ?>
<?php echo $form->passwordField($model,'password2',array('class'=>'inputbox grid-11-12')); ?>
<?php echo $form->error($model,'password2'); ?>
</div>
<div class="elem">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="elem">
<label for="content">User Image:</label>
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>Yii::app()->request->baseUrl .'/backend.php/user/upload',
'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>3*1024*1024,// maximum file size in bytes
'minSizeLimit'=>50*1024,// minimum file size in bytes
'multiple'=>false,
//'onComplete'=>Yii::app()->request->baseUrl .'/backend.php/user/saveStuff/?fn='. "js:function(id, fileName, responseJSON){ alert(fileName); }",
//'messages'=>array(
// 'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
// 'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
// 'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
// 'emptyError'=>"{file} is empty, please select files again without it.",
// 'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
// ),
//'showMessage'=>"js:function(message){ alert(message); }"
)
)); ?>
</div>
This is the controller ..
<?php
class UserController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column1';
public $image;
.......
public function actions()
{
return array(
'upload' => array(
'class' => 'ext.actions.uploadAction',
),
);
}
........
public function actionCreate()
{
$model=new User;
$profile=new UserProfile;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$profile->attributes=$_POST['UserProfile'];
if(!$this->saveUser($model, $profile))
Yii::app()->user->setFlash('error', 'Not Saved :)!');
}
$this->render('create',array(
'model'=>$model,
'profile'=>$profile,
));
}
public function saveUser($model, $profile)
{
$userValid = $model->validate();
$profileValid = $profile->validate();
$valid = $userValid && $profileValid;
if($valid)
{
$model->save(false);
$profile->user_id = $model->id;
$profile->image = !is_null($this->image)? $this->image : null; // name of image file which uploaded
$profile->save(false);
Yii::app()->user->setFlash('success', 'Saved :)!');
$this->redirect(array('index'));
return true;
}
return false;
}
}
the external action in details is:
<?php
class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
Yii::import("ext.EAjaxUpload.qqFileUploader");
// make the directory to store the pic:
$folder=Yii::getPathOfAlias('webroot') .'/images/' . $this->controller->id . '/';// folder for uploaded files
if(!is_dir($folder))
{
mkdir($folder);
chmod($folder, 0755);
// the default implementation makes it under 777 permission, which you could possibly change
//recursively before deployment, but here's less of a headache in case you don't
}
$allowedExtensions = array("jpg");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
$this->controller->image = $fileName; // ??????
echo $return;// it's array
}
}
do this:
$this->controller->image = $fileName; // this line does not work!!
$this->controller->renderText($this->controller->image);
I bet this will display the $fileName.
Where do you try to access the controllers image property?
Values are not preserved between requests.
I've done something similar to this using a callback.
So in my controller actions() configuration I have a line:
'onSuccessCallback' => 'myCallback'
In my action class, at the end of run() I have:
call_user_func( array($this->getController(),$this->onSuccessCallback), $fileName);
In the controller I have
function myCallback($fileName)
{
this->image = $fileName;
}
I can then access the property from the controller via
$this->image