在symfony中利用jpgraph实现验证码功能
在symfony中利用jpgraph实现验证码功能
今天刚好用到验证码,在symfony的wiki找到一个解决的方法,记录下来。
这个方法其实使用的是大名鼎鼎的jpgraph的库,由于有jpgraph的插件,安装很容易:
首先到你的项目根目录执行下面的命令,利用svn命令行工具下载这个插件
svn co http://svn.symfony-project.com/plugins/sfJpGraphPlugin ./plugins/sfJpGraphPlugin
如果你的项目使用svn管理,请设定sfJpGraphPlugin目录的属性:
svn propedit svn:externals plugins
输入:
sfJpGraphPlugin http://svn.symfony-project.com/plugins/sfJpGraphPlugin
ok,jpgraph插件安装完了。
验证码部分
动作:
class profileActions extends sfActions
{
public function executeRegister()
{
if ($this->getRequest()->getMethod() == sfRequest::POST) {
// process form
}
require_once 'jpgraph/jpgraph_antispam.php';
$antispam = new AntiSpam();
$antispam_string = $antispam->rand(5);
$this->getUser()->setAttribute('antispam', $antispam_string);
}
public function executeAntispam() {
if (!$string = $this->getUser()->getAttribute('antispam')) {
return sfView::NONE;
}
$this->getResponse()->setContentType('image/jpeg');
$antispam = new AntiSpam($string);
echo $antispam->stroke();
return sfView::NONE;
}
}
模版:
<label>Picture</label>
<img src="http://www.jiangle.name/wp-admin/%3C?php%20echo%20url_for%28%27profile/antispam%27%29;%20?%3E" />
验证类:myCharactersValidator.class.php
class myCharactersValidator extends sfValidator
{
public function execute (&$value, &$error)
{
$string = sfContext::getInstance()->getUser()->getAttribute('antispam');
if ($value != $string) {</php>// generate a new image....
$antispam = new AntiSpam();
$antispam_string = $antispam->rand(5);
sfContext::getInstance()->getUser()->setAttribute('antispam', $antispam_string);$error = $this->getParameter('characters_error');
return false;
}
return true;
}
}
[[i] 本帖最后由 symfony 于 2007-6-16 20:17 编辑 [/i]]