1

View1.ctp というビューがあります。このビューでは、ビューが captcha.ctp である「Captcha」というコントローラー関数を呼び出しています。ビュー captcha.ctp に $text という変数があります。この $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); 
           ?>
4

1 に答える 1

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());

「期待される」値は Session キーに保存されvercodeます。これは、フォーム処理ロジックで PostsController から読み取ることもできます。

于 2013-02-26T10:21:14.853 に答える