Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, July 3, 2012

All about validation in Yii - PART1

Validation in YII (Server side & Client Side)- PART 1

Yii support server side validation &  client side validation and it has wide range of built in validators, here we are going to see the each and every points about validation features that Yii provide.

Declaring Validation Rules

We specify the validation rules in Model class through the rules() method which should return an array of rule configurations. validators are called in order if we specified more than one validator for attribute
rules() method is a default method that triggers yii validation by using rules() method while validate() called. validate() function triggered automatically while we call $model->save() orcall $model->validate().

Validation rule syntax

array('AttributeList', 'Validator', 'on'=>'ScenarioList'...), 

Here AttributeList defines the list of model attributes, if more than one attribute it should be separated by comma.
Validator defines type of validation to be done yii provides the built in validators for email, url and so on refer table 1 for built in validators.
ScenarioList tells on which scenario the validation rule should fire, more than one scenario will be separated by comma.

Adding validations to model

        public function rules(){
        return array('username','required');

the above validation rule tells the yii to validate username fields to be mandatory through required validator. we apply same validation rule for  more than one field, by separating them with comma
        public function rules(){
        return array('username,password','required');

in the above example we set username and password field to be mandatory and we can apply more than validation to same attribute
        public function rules(){
        return array(
        array('username','length','min'=>3, 'max'=>12);        

Above example tells yii to validate username attribute length should have 3-12 and it is required.

Yii triggers validation when we call $model->validate(); or $model->save(); While saving records validation automatically called by default, if validation should be avoided in save methods $model->save(false); //which cancels validation

Clear steps

Model Finally model looks likes this
        class LoginForm extends CFormModel
        public $username;
        public $password;        
        public function rules()
        return array(
        array('username, password', 'required'),
        array('username','length','min'=>3, 'max'=>12);

$model = new Users();

Trigger Validation

to get particular field validation error, Yii add these statements to view by default why we scaffolding our code.

<?php echo $form->error($model, 'username'); ?> 
To get error summary for all fields
<?php echo $form->errorSummary($model); ?>

Contd.. on PART II

Tuesday, June 26, 2012

Handling Scripts and CSS in Yii Framework

Handling Scripts and CSS in Yii Framework

Yii provide CClientScript to manage the scripts and css files in Yii.

Registering Core scripts that comes with Yii

To register the core jquery library that comes with yii, use the following methods.

Yii::app()->clientScript->registerCoreScript( 'jquery.ui' );
//We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality

The above statement register the Jquery library and jquery ui, if YII_DEBUG is false then yii will register minimized version of Jquery & Jquery UI library.

To register inline scripts and css files
Yii::app()->clientScript->registerScript('unique scriptname','js code',position)

Yii::app()->clientScript->registerCss('unique css','csscode','media=>print/handheld/screen')

Script Positions

CClientScript::POS_HEAD : the script is inserted in the head section right before the title element. .
CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
CClientScript::POS_END : the script is inserted at the end of the body section.
CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
CClientScript::POS_READY : the script is inserted in the jQuery's ready function.

so if you use,
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/script/test.js',CClientScript::POS_END);
then the script will be inserted to the body section

To register external scripts and css files

Yii::app()->clientScript->registerCssFile($yourscript_asset. '/test.css');
Yii::app()->clientScript->registerScriptFile($yourscript_asset. '/test.js')

Publishing scripts to assets directory

Asset manager in brief

CAssetManager is a Web application component that manages private files (called assets) and makes them accessible by Web clients. It achieves this goal by copying assets to a Web-accessible directory and returns the corresponding URL for accessing them.
you can compress and minify and otherwise process your assets with the asset publishing system, and it makes it easier to host your JS and CSS on a CDN since it's separate from your codebase.With assets, a component can be used easily without worrying about what files to be copied to public directories and what their URLs are
Consider a scenario, if we have two scripts which is located in scripts/testscript, the directory has two files namely test.js and test.css. We are going to publish it to asset and then we consume that files from asset directory, here is the snippet
$yourscript_asset= Yii::app()->assetManager->publish(Yii::app()->basePath . '/scripts/testscript /');

//Register JS and CSS files        
Yii::app()->clientScript->registerCssFile($yourscript_asset. '/test.css');
Yii::app()->clientScript->registerScriptFile($yourscript_asset. '/test.js');


Load files from google server

Cleans all registered scripts before any script register

Cleans all registered scripts.

Prevent loading jquery files

Yii::app()->clientScript->scriptMap['jquery.js'] = false;
//or if more than one script to be prevent from registering

Avoiding scripts download on AJAX renderPartial request

Suppose we created a function to display the AJAX active form and its contents are returned by a call to a controller’s action that will partially render a view.
// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();
Now controller doesn't return script files.
It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won’t stop the duplication of the script.

Monday, August 8, 2011

Enable GZIP in PHP Application

Already i shown how to enable GZIP in YII Framework application, To enable GZIP in general PHP Application include the below code at the top of the document you want to gzip:

if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) && substr_count( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) )
 ob_start( 'ob_gzhandler' );

Deleting files in server without any error using php

To delete files in server and avoid "denied access to file" error to unlink file.

To delete file, you must to change file's owernship .

An example:


How to minify Javascript, CSS files automatically in YII Framework

We are going to reduce the HTTP calls for resources files by merging several resources files into a single (or more) files, so that the application load faster. E Client Script can automatically detect the required list of files, and generate a unique filename hash, so boldly ease of use.

CSS Files:

CSS files are merged based on there media attribute, background images with a relative path in file can also be displayed correctly.

Script files:

Script files are merged based on their position, If you use the 'CClientScript::POS_HEAD' you will end up with a single file for all the script files you've used on that page.

If you use 'CClientScript::POS_HEAD' and 'CClientScript::POS_END' for example then you'll end up with two files for each page on that request, Since those resources are located in different positions.

Add the following code to components array in protected/config/main.php

Add to configuration:
First you have to download EClientScript extension

 'clientScript' => array(
            'class' => 'ext.minify.EClientScript',
            'combineScriptFiles' => true,
            'combineCssFiles' => true,
            'optimizeCssFiles' => true,
            'optimizeScriptFiles' => false,

Then you'd use the regular 'registerScriptFile' & 'registerCssFile' methods as normal and the files will be combined automatically

Friday, August 5, 2011

Module based login in YII Framework

Module based login

What is module?

From YII Framework documentation

 "A module is a self-contained software unit that consists of models, views, controllers and other supporting components. In many aspects, a module resembles to an application. The main difference is that a module cannot be deployed alone and it must reside inside of an application. Users can access the controllers in a module like they do with normal application controllers.

Modules are useful in several scenarios. For a large-scale application, we may divide it into several modules, each being developed and maintained separately. Some commonly used features, such as user management, comment management, may be developed in terms of modules so that they can be reused easily in future projects."

For example
admin users   = > index.php?r=admin/default/login
general users => index.php?r=user/default/login

To add module based login to a site without using RBAC, please follow these guidelines.
Consider the situation where we want to add 3 types of login in a site: customer, dealer, and admin.

Start by generating three modules using GII. (To do this, please refer to this guide for module generation

Step 1
Copy the UserIdentity component to the module/components folder for each module. We will validate each module against its table. For example, customer validation is done using customer table, and admin validation against the admin table

For each module, change its UserIdentity authenticate() function to perform the appropriate validation.

Step 2
For each module, add the following lines to its main page. For example, for the Customer module, add to Customer/CustomerModule.php Add the following lines to init():

'errorHandler' => array(
'errorAction' => 'customer/default/error'),
'user' => array(
'class' => 'CWebUser',             
'loginUrl' => Yii::app()->createUrl('customer/default/login'),


Step 3
Create the login/logout action in each module's DefaultController.
For example, for the Customer module:
Create the actionLogin() in Customer/controllers/DefaultController.php.
Also, create actionLogout() as follows:

public function actionLogout() {

Point sub-domain to module
This tips from the forum URL Subdomain to module
There is a feature called "Parameterizing Hostnames" (described on this pages). add the following lines to main.php

'components' => array(
'urlManager' => array(
'rules' => array(
'' => 'customer/default/index',
'' => 'customer/default/login',
So "customer/default/index" refers to the module "customer" with controller "default" and action "index".

Redirect to respective module login, if user not logged in to a particular model
add following code to customer module CustomerModule.php in beforeControllerAction

do the same for other module
in SiteController's site/login method
public function actionLogin() {

Another method(Recommended)
Redirect to respective module login, if user not logged in to a particular model
add following code to customer module CustomerModule.php
public function beforeControllerAction($controller, $action) {
if (parent::beforeControllerAction($controller, $action)) {
// this method is called before any module controller action is performed
// you may place customized code here
$route = $controller->id . '/' . $action->id;
// echo $route;
$publicPages = array(
if (Yii::app()->user->isGuest && !in_array($route, $publicPages)){            
return true;
return false;

do the same for other module
Thanks to ricardograna for sharing some configurations

Tuesday, August 10, 2010

Fixing Internet explorer Content-type and Content-Disposition issues using PHP

When you add download files option to your pages using PHP. you need to use following code to fix IE related issues

$filename = "myfile" . ".doc";
header('Content-Type: application/msword');
header('Expires: ' . gmdate('D, d M Y H:i:s') . 'GMT');
header('Content-Disposition: attachment; filename="' . $filename . '"');

if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header('Pragma: no-cache');

Tuesday, July 22, 2008

Clean URL

Clean URLs for a better search engine ranking From : Content with style

Search engines are often key to the successful promotion and running of your website, with high traffic making or breaking your online business. To maximise the visibility of your site in the organic listings of the biggest search engines it is important to strategically work out how keywords are used.

While link building (placing links to the site or from the site) and, most importantly, writing useful content form the foundation of search engine rankings, some careful attention to how your site treats URLs will influence its ranking massively.

Read More>>

Let's suppose you are building a small database driven website or web-based application which you need search engine covery for. And this isn't the only reason why you would choose to create a web application with search engine friendly URLs. Another important aspect is the usability of this feature. To achieve this, you could use Apache's mod-rewrite module. This would be one way. Another way would be to implement a sort of URL rewrite engine into your web application's engine.

Read More>>

How to make URLs user-friendly

One of the worst elements of the web from a user interface standpoint is the URL. However, if they're short, logical, and self-correcting, URLs can be acceptably usable.

Read more>>

Making "clean" URLs with Apache and PHP

Nowadays we almost systematically create database-generated websites. URLs are thus written on-the-fly and we usually call pages through query string, like:

What I call "clean" URLs is what you can see on, for instance. In my example the URL would be: