我有一个名为View1.ctp的视图。在这个视图中我调用了一个名为'Captcha'的控制器函数,其中的视图是captcha.ctp。我有一个名为$ text的变量,在视图中,captcha.ctp.I想要访问这个$ text变量在我的view1.ctp中。我该怎么办?
(注:Cakephp版本-2.3)
View1.ctp
<h1>Add Comment</h1>
<?php
$post_id= $posts['Post']['id'];
echo $this->Form->create('Comment',array('action' => 'comment','url' => array($post_id,$flag)));
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('text', array('rows' => '3'));
echo "Enter Captcha Code: ";
echo $this->Html->image(
array('controller' => 'posts', 'action' => 'captcha'));
echo $this->Form->input('code');
echo $this->Form->end('Add comment');
?>
captcha.ctp:
<?php
$this->Session->read();
$text = rand(10000,99996);
$_SESSION["vercode"] = $text;
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
?>
答案 0 :(得分:0)
更好的方法是将Captcha视图改为Helper,这更合适。所以将captcha.ctp移动到app / View / Helper / CaptchaHelper.php,并将其内容包装在一个类中,如:
<?php
App::uses('AppHelper', 'View/Helper');
class CaptchaHelper extends AppHelper {
function create() {
// This line doesn't make much sense as no data from the session is used
// $this->Session->read();
$text = rand(10000, 99996);
// Don't use the $_SESSION superglobal in Cake apps
// $_SESSION["vercode"] = $text;
// Use SessionComponent::write instead
$session = new SessionComponent(new ComponentCollection());
$session->write('vercode', $text);
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
// Return the generated image
return imagejpeg($image_p, null, 80);
}
}
然后在PostsController中,将Captcha
添加到帮助程序数组:
public $helpers = array('Captcha');
(或者如果你已经有一个帮助器数组,只需将它附加到该数组。)
然后从View1.ctp中,您可以调用帮助程序返回图像:
echo $this->Html->image($this->Captcha->create());
它的“预期”值将存储在会话密钥vercode
中,您也可以在表单处理逻辑中从PostsController中读取它。