Yii框架之表单引入jquery、登陆实现、密码加密、登陆状态设置、验证码使用、前后台管理员的区分、session和cookie的操作、别名的介绍

【用户注册验证】

通过小物件创建form表单  [view]

收集表单数据 attributes(foreach的封装)  [controller]

表单数据验证  rules()   [model]






复选框验证




$user_model -> attributes = $_POST['User'];

attributes这个属性在使用的时候会收集表单信息并赋予模型属性里边

该属性是和rules()方法一并使用,只有在rules()里边设置了验证规则的属性才可以被attributes接收

如果有的属性没有具体验证规则,则给一个safe规则。

确认密码验证

label  与  labelEx区别

如果有的选项是必填项(例如用户名、密码),那么labelEx会有一个”*星号标识,label就没有

表单验证:

rules()放进行数据验证

两类:一个是系统已经定义好的验证类,另一个是我们自己在模型里边定义好的具体验证方法进行验证

【引入jquery进行数据验证】


有的项目是jquery本身无法验证的,那么就会跑到服务器继续验证。

【用户登录系统实现】

1. 制作表单

2. 收集表单数据(用户名、密码)

3. 去数据库校验用户名和密码

4. 用户信息session持久化

 

Yii框架里边有两个模型:数据模型、表单模型

数据模型:与数据库进行交互的模型model(例如good模型、user模型)

表单模型:收集用户信息,然后丢弃。

 

我们要使用登录表单模型来进行用户登录系统功能实现

登录模型操作与数据模型是一致的,不同的是,登录模型不与数据库进行交互。


表单数据校验save()方法可以一边校验数据,校验成功可以存储数据

save()   到后边有一个环节会执行模型的rules()方法,也就校验表单了

 

我们现在实现用户登录需要校验,可以调用validate(),该方法可以校验我们输入的信息。

validate() 该方法在执行到后边 也会去执行rules()方法,进行表单的校验

 

save()

validate()

rules()

save()方法执行会执行validate()方法,后边也会执行rules()方法







持久化用户信息login




用户登录系统:

表单

在控制器里边收集信息

验证用户信息:模型->validate()来验证用户信息,与表单验证是一致的

用户信息真实性:rules()方法里边有自定义一个方法来验证authenticate()

具体通过用户验证组件UserIdentity来验证的,这个组件里边也有一个方法authenticate()方法进行验证

 

持久化用户信息:模型调用login()方法来持久化。

Yii框架前台用户注册、用户登录系统实现

校验用户名和密码

使用组件UserIdentity对用户名和密码进行校验

用户名存储到session里边,通过用户验证组件CwebUser  à  login();

用户注册用户名密码md5加密


记住用户(2周不用重复登录)

红色的”*星号是css控制的

记住登录状态

这样下次再登录网站的时候,就不用重复输入用户名和密码。

是浏览器的cookie把状态给记住了。

 

通过图解查看Yii框架如何实现记录登陆状态

实现:

1. 制作表单

2. 实现model模型

Cookie的名字和值,在框架里边已经设置好了,无需关心。


1. 制作表单

2. 设计模型(rules()   login()   attributeLabels())

用户登录系统验证码设置

Gd2画图工具

验证编码信息:随机数

验证码具体验证原理:

画图的同时就把验证编码进行session存储,用户输入的验证码信息与我们session里边存放的信息做比较。

实现:

1. 制作表单


如何使用该核心类:

在控制器里边使用。





表单部分与控制器部分的联系:

$this->widget(CCaptcha);  会间接调用控制器的方法  路由user/captcha


在登录模型里边对验证码进行校验:

captcha会简介找到CcaptchaAction进行验证码的比较。

 

验证码使用步骤:

1. 控制器设置actions方法

2. 表单里边通过widget显示验证码

3. 模型里边通过captcha校验验证码

<?php $this -> widget('CCaptcha'); ?>  会简介访问路由  user/captcha  CcaptchaAction

array('verifyCode','captcha','message'=>'请输入正确的验证码'),  简介通过CcaptchaAction进行校验。

后台用户登录系统

1. 复习前台用户登录系统

2. 区分前台、后台用户信息(session区分)

为添加的数据表创建模型model

现在出现一个问题:前台登录用户信息与后台用户登录系统有混淆。

为后台管理员登陆系统设置session前缀信息 houtaiModule.php

Yii框架中session的使用

设置、使用、删除

cookieYii框架中的使用

路径别名

Yii框架里边有许多地方使用路径别名:

System  application   zii  等等


总结:

用户登录系统

记住登录状态(rememberMe

验证码 (控制器、视图、验证模型)

后台管理员登录系统(为用户登录session信息设置前缀 houtaimodule.php设置)

 会话控制session  cookie的使用

session设置了前缀,前后台,读取用户名的时候,代码是一样的,yii框架是怎么区分前缀的?

我们读取用户登录信心通过CwebUser读取

Yii::app()->user->name;  //获得name信息的时候会自动设置当前user用户组件的session前缀


CCaptchaAction.php

<?php

/**
 * CCaptchaAction class file.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

/**
 * CCaptchaAction renders a CAPTCHA image.
 *
 * CCaptchaAction is used together with {@link CCaptcha} and {@link CCaptchaValidator}
 * to provide the {@link http://en.wikipedia.org/wiki/Captcha CAPTCHA} feature.
 *
 * You must configure properties of CCaptchaAction to customize the appearance of
 * the generated image.
 *
 * Note, CCaptchaAction requires PHP GD2 extension.
 *
 * Using CAPTCHA involves the following steps:
 * <ol>
 * <li>Override {@link CController::actions()} and register an action of class CCaptchaAction with ID 'captcha'.</li>
 * <li>In the form model, declare an attribute to store user-entered verification code, and declare the attribute
 * to be validated by the 'captcha' validator.</li>
 * <li>In the controller view, insert a {@link CCaptcha} widget in the form.</li>
 * </ol>
 *
 * @property string $verifyCode The verification code.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package system.web.widgets.captcha
 * @since 1.0
 */
class CCaptchaAction extends CAction
{
	/**
	 * The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
	 */
	const REFRESH_GET_VAR='refresh';
	/**
	 * Prefix to the session variable name used by the action.
	 */
	const SESSION_VAR_PREFIX='Yii.CCaptchaAction.';
	/**
	 * @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.
	 * A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
	 */
	public $testLimit = 3;
	/**
	 * @var integer the width of the generated CAPTCHA image. Defaults to 120.
	 */
	public $width = 120;
	/**
	 * @var integer the height of the generated CAPTCHA image. Defaults to 50.
	 */
	public $height = 50;
	/**
	 * @var integer padding around the text. Defaults to 2.
	 */
	public $padding = 2;
	/**
	 * @var integer the background color. For example, 0x55FF00.
	 * Defaults to 0xFFFFFF, meaning white color.
	 */
	public $backColor = 0xFFFFFF;
	/**
	 * @var integer the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
	 */
	public $foreColor = 0x2040A0;
	/**
	 * @var boolean whether to use transparent background. Defaults to false.
	 */
	public $transparent = false;
	/**
	 * @var integer the minimum length for randomly generated word. Defaults to 6.
	 */
	public $minLength = 6;
	/**
	 * @var integer the maximum length for randomly generated word. Defaults to 7.
	 */
	public $maxLength = 7;
	/**
	 * @var integer the offset between characters. Defaults to -2. You can adjust this property
	 * in order to decrease or increase the readability of the captcha.
	 * @since 1.1.7
	 **/
	public $offset = -2;
	/**
	 * @var string the TrueType font file. Defaults to Duality.ttf which is provided
	 * with the Yii release.
	 */
	public $fontFile;
	/**
	 * @var string the fixed verification code. When this is property is set,
	 * {@link getVerifyCode} will always return this value.
	 * This is mainly used in automated tests where we want to be able to reproduce
	 * the same verification code each time we run the tests.
	 * Defaults to null, meaning the verification code will be randomly generated.
	 * @since 1.1.4
	 */
	public $fixedVerifyCode;

	/**
	 * Runs the action.
	 */
	public function run()
	{
            $this -> fixedVerifyCode = substr(md5(mt_rand(1,10000)),0,4);
		if(isset($_GET[self::REFRESH_GET_VAR]))  // AJAX request for regenerating code
		{
			$code=$this->getVerifyCode(true);
			echo CJSON::encode(array(
				'hash1'=>$this->generateValidationHash($code),
				'hash2'=>$this->generateValidationHash(strtolower($code)),
				// we add a random 'v' parameter so that FireFox can refresh the image
				// when src attribute of image tag is changed
				'url'=>$this->getController()->createUrl($this->getId(),array('v' => uniqid())),
			));
		}
		else
			$this->renderImage($this->getVerifyCode());
		Yii::app()->end();
	}

	/**
	 * Generates a hash code that can be used for client side validation.
	 * @param string $code the CAPTCHA code
	 * @return string a hash code generated from the CAPTCHA code
	 * @since 1.1.7
	 */
	public function generateValidationHash($code)
	{
		for($h=0,$i=strlen($code)-1;$i>=0;--$i)
			$h+=ord($code[$i]);
		return $h;
	}

	/**
	 * Gets the verification code.
	 * @param boolean $regenerate whether the verification code should be regenerated.
	 * @return string the verification code.
	 */
	public function getVerifyCode($regenerate=false)
	{
		$session = Yii::app()->session;
		$session->open();
		$name = $this->getSessionKey();
                
                
		if($this->fixedVerifyCode !== null) {
                    	$session[$name] = $this->fixedVerifyCode;
			$session[$name . 'count'] = 1;
                }

		if($session[$name] === null || $regenerate)
		{
			$session[$name] = $this->generateVerifyCode();
			$session[$name . 'count'] = 1;
		}
		return $session[$name];
	}

	/**
	 * Validates the input to see if it matches the generated code.
	 * @param string $input user input
	 * @param boolean $caseSensitive whether the comparison should be case-sensitive
	 * @return boolean whether the input is valid
	 */
	public function validate($input,$caseSensitive)
	{
		$code = $this->getVerifyCode();
		$valid = $caseSensitive ? ($input === $code) : !strcasecmp($input,$code);
		$session = Yii::app()->session;
		$session->open();
		$name = $this->getSessionKey() . 'count';
		$session[$name] = $session[$name] + 1;
		if($session[$name] > $this->testLimit && $this->testLimit > 0)
			$this->getVerifyCode(true);
		return $valid;
	}

	/**
	 * Generates a new verification code.
	 * @return string the generated verification code
	 */
	protected function generateVerifyCode()
	{
		if($this->minLength < 3)
			$this->minLength = 3;
		if($this->maxLength > 20)
			$this->maxLength = 20;
		if($this->minLength > $this->maxLength)
			$this->maxLength = $this->minLength;
		$length = mt_rand($this->minLength,$this->maxLength);

		$letters = 'bcdfghjklmnpqrstvwxyz';
		$vowels = 'aeiou';
		$code = '';
		for($i = 0; $i < $length; ++$i)
		{
			if($i % 2 && mt_rand(0,10) > 2 || !($i % 2) && mt_rand(0,10) > 9)
				$code.=$vowels[mt_rand(0,4)];
			else
				$code.=$letters[mt_rand(0,20)];
		}

		return $code;
	}

	/**
	 * Returns the session variable name used to store verification code.
	 * @return string the session variable name
	 */
	protected function getSessionKey()
	{
		return self::SESSION_VAR_PREFIX . Yii::app()->getId() . '.' . $this->getController()->getUniqueId() . '.' . $this->getId();
	}

	/**
	 * Renders the CAPTCHA image based on the code.
	 * @param string $code the verification code
	 * @return string image content
	 */
	protected function renderImage($code)
	{
		$image = imagecreatetruecolor($this->width,$this->height);

		$backColor = imagecolorallocate($image,
				(int)($this->backColor % 0x1000000 / 0x10000),
				(int)($this->backColor % 0x10000 / 0x100),
				$this->backColor % 0x100);
		imagefilledrectangle($image,0,0,$this->width,$this->height,$backColor);
		imagecolordeallocate($image,$backColor);

		if($this->transparent)
			imagecolortransparent($image,$backColor);

		$foreColor = imagecolorallocate($image,
				(int)($this->foreColor % 0x1000000 / 0x10000),
				(int)($this->foreColor % 0x10000 / 0x100),
				$this->foreColor % 0x100);

		if($this->fontFile === null)
			$this->fontFile = dirname(__FILE__) . '/Duality.ttf';

		$length = strlen($code);
		$box = imagettfbbox(30,0,$this->fontFile,$code);
		$w = $box[4] - $box[0] + $this->offset * ($length - 1);
		$h = $box[1] - $box[5];
		$scale = min(($this->width - $this->padding * 2) / $w,($this->height - $this->padding * 2) / $h);
		$x = 10;
		$y = round($this->height * 27 / 40);
		for($i = 0; $i < $length; ++$i)
		{
			$fontSize = (int)(rand(26,32) * $scale * 0.8);
			$angle = rand(-10,10);
			$letter = $code[$i];
			$box = imagettftext($image,$fontSize,$angle,$x,$y,$foreColor,$this->fontFile,$letter);
			$x = $box[2] + $this->offset;
		}

		imagecolordeallocate($image,$foreColor);

		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Content-Transfer-Encoding: binary');
		header("Content-type: image/png");
		imagepng($image);
		imagedestroy($image);
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值