2013-02-26 84 views
1

我有一個名爲View1.ctp的視圖。在這個視圖中我調用一個名爲'Captcha'的控制器函數,其視圖是captcha.ctp。我有一個名爲$ text的變量查看captcha.ctp.I想在我的view1.ctp中訪問這個$ text變量,我應該怎麼做? (注:CakePHP的版本-2.3) View1.ctp在另一個視圖中訪問視圖變量-Cakephp

 <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

一種更好的方法是打開驗證碼查看成Helper代替,這是更合適的。所以移動captcha.ctp到應用程序/查看/助手/ 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中讀取該值。

+0

非常感謝。請試試看,並讓你知道先生 – user1479469 2013-02-26 10:25:22

+0

,但先生我需要訪問另一個控制器中的這個vercode CommentsController.php不在PostsController.ctp – user1479469 2013-02-26 10:32:33

+0

我得到這個錯誤sir.Error:調用成員函數在非對象上讀取() – user1479469 2013-02-26 10:36:42

相關問題