Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: Вывод данных из сессии

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Без описания
stdm
Отправлено: 02 Июля, 2013 - 08:22:38
Post Id


Новичок


Покинул форум
Сообщений всего: 5
Дата рег-ции: Янв. 2013  


Помог: 0 раз(а)




Добрый день.
Помогите разобраться с порядком вывода данных на html страницу из сессии.

Директория, с 3-мя файлами. Файл с классом генерации капчи(kcaptcha‎), index.php - создание экземпляра класса и вывод капчи, form.html - форма, с обращением к index.php для вывода картинки капчи. При генерации капчи, набор символов сохраняется в переменной сессии.

Код формы:
CODE (htmlphp):
скопировать код в буфер обмена
  1. <?php
  2.  
  3. if(!empty($_POST['keystring'])){
  4.        
  5.                 if($_POST['keystring'] === $_SESSION['captcha'])
  6.                         echo 'OK';
  7.                
  8.                 else
  9.                         echo 'BAD';
  10.         }
  11.  
  12. echo $_SESSION['captcha'];
  13. ?>
  14. <form action="" method="post">
  15. <p>Enter text shown below:</p>
  16. <p><img src="http://test1.ru/captcha/index.php"></p>
  17. <p><input type="text" name="keystring"></p>
  18. <p><input type="submit" value="Check"></p>
  19. </form>
  20.  
  21. <?php
  22.         echo $_SESSION['captcha'];
  23. ?>


Почему при таком коде формы, после обращения к index.php, когда капча сгенерирована, выведена на страницу и ее символы сохранены в сессии, echo $_SESSION['captcha'] выдает пустую строку?

По логике ведь должен выдать после обращения к index.php, уже сохраненные даннные.
echo $_SESSION['captcha'] - пустая строка
<img src="http://test1.ru/captcha/index.php"> - генерация новой капчи
echo $_SESSION['captcha'] - символы капчи

При этом после отправки формы, скрипт корректно сравнивает значение из формы со значением сессии.
 
 Top
imya
Отправлено: 02 Июля, 2013 - 08:40:44
Post Id



Участник


Покинул форум
Сообщений всего: 1472
Дата рег-ции: Сент. 2012  
Откуда: Запорожье, Украина


Помог: 19 раз(а)




А где у вас сама запись капчи в сессию-то?


-----
PHP:
скопировать код в буфер обмена
  1. do {box != cat;} while (cat != box);


Когда нормальный человек, уезжая из дома одевает на жену пояс верности, веб-дизайнер ставит на нее счетчик...
 
My status
 Top
stdm
Отправлено: 02 Июля, 2013 - 09:21:14
Post Id


Новичок


Покинул форум
Сообщений всего: 5
Дата рег-ции: Янв. 2013  


Помог: 0 раз(а)




класс генерирующий капчу

CODE (htmlphp):
скопировать код в буфер обмена
  1. <?php
  2.  
  3. # KCAPTCHA PROJECT VERSION 2.0
  4. # Automatic test to tell computers and humans apart
  5. # Copyright by Kruglov Sergei, 2006, 2007, 2008, 2011
  6. # www.captcha.ru, www.kruglov.ru
  7. # System requirements: PHP 4.0.6+ w/ GD
  8. # KCAPTCHA is a free software. You can freely use it for developing own site or software.
  9. # If you use this software as a part of own sofware, you must leave copyright notices intact or add KCAPTCHA copyright notices to own.
  10. # As a default configuration, KCAPTCHA has a small credits text at bottom of CAPTCHA image.
  11. # You can remove it, but I would be pleased if you left it. ;)
  12. # See kcaptcha_config.php for customization
  13. class KCAPTCHA{
  14.  
  15.         // generates keystring and image
  16.         function KCAPTCHA(){
  17.        
  18.        
  19.                 # KCAPTCHA configuration file
  20.                 $alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; # do not change without changing font files!
  21.                 # symbols used to draw CAPTCHA
  22.                 //$allowed_symbols = "0123456789"; #digits
  23.                 //$allowed_symbols = "23456789abcdegkmnpqsuvxyz"; #alphabet without similar symbols (o=0, 1=l, i=j, t=f)
  24.                 $allowed_symbols = "23456789abcdegikpqsvxyz"; #alphabet without similar symbols (o=0, 1=l, i=j, t=f)
  25.                 # folder with fonts
  26.                 $fontsdir = 'fonts';   
  27.  
  28.                 # CAPTCHA string length
  29.                 $length = mt_rand(5,7); # random 5 or 6 or 7
  30.                 //$length = 6;
  31.  
  32.                 # CAPTCHA image size (you do not need to change it, this parameters is optimal)
  33.                 $width = 160;
  34.                 $height = 80;
  35.  
  36.                 # symbol's vertical fluctuation amplitude
  37.                 $fluctuation_amplitude = 8;
  38.  
  39.                 #noise
  40.                 //$white_noise_density=0; // no white noise
  41.                 $white_noise_density=1/6;
  42.                 //$black_noise_density=0; // no black noise
  43.                 $black_noise_density=1/30;
  44.  
  45.                 # increase safety by prevention of spaces between symbols
  46.                 $no_spaces = true;
  47.  
  48.                 # show credits
  49.                 $show_credits = true; # set to false to remove credits line. Credits adds 12 pixels to image height
  50.                 $credits = 'www.captcha.ru'; # if empty, HTTP_HOST will be shown
  51.                 # CAPTCHA image colors (RGB, 0-255)
  52.                 //$foreground_color = array(0, 0, 0);
  53.                 //$background_color = array(220, 230, 255);
  54.                 $foreground_color = array(mt_rand(0,80), mt_rand(0,80), mt_rand(0,80));
  55.                 $background_color = array(mt_rand(220,255), mt_rand(220,255), mt_rand(220,255));
  56.  
  57.                 # JPEG quality of CAPTCHA image (bigger is better quality, but larger file size)
  58.                 $jpeg_quality = 90;
  59.  
  60.                 //require(dirname(__FILE__).'/kcaptcha_config.php');
  61.                 $fonts=array();
  62.                 $fontsdir_absolute=dirname(__FILE__).'/'.$fontsdir;
  63.                 if ($handle = opendir($fontsdir_absolute)) {
  64.                         while (false !== ($file = readdir($handle))) {
  65.                                 if (preg_match('/\.png$/i', $file)) {
  66.                                         $fonts[]=$fontsdir_absolute.'/'.$file;
  67.                                 }
  68.                         }
  69.                     closedir($handle);
  70.                 }      
  71.        
  72.                 $alphabet_length=strlen($alphabet);
  73.                
  74.                 do{
  75.                         // generating random keystring
  76.                         while(true){
  77.                                 $this->keystring='';
  78.                                 for($i=0;$i<$length;$i++){
  79.                                         $this->keystring.=$allowed_symbols{mt_rand(0,strlen($allowed_symbols)-1)};
  80.                                 }
  81.                                 if(!preg_match('/cp|cb|ck|c6|c9|rn|rm|mm|co|do|cl|db|qp|qb|dp|ww/', $this->keystring)) break;
  82.                         }
  83.                         unset($_SESSION['captcha']);
  84.                         $_SESSION['captcha'] = $this->keystring;
  85.                         $font_file=$fonts[mt_rand(0, count($fonts)-1)];
  86.                         $font=imagecreatefrompng($font_file);
  87.                         imagealphablending($font, true);
  88.  
  89.                         $fontfile_width=imagesx($font);
  90.                         $fontfile_height=imagesy($font)-1;
  91.                        
  92.                         $font_metrics=array();
  93.                         $symbol=0;
  94.                         $reading_symbol=false;
  95.  
  96.                         // loading font
  97.                         for($i=0;$i<$fontfile_width && $symbol<$alphabet_length;$i++){
  98.                                 $transparent = (imagecolorat($font, $i, 0) >> 24) == 127;
  99.  
  100.                                 if(!$reading_symbol && !$transparent){
  101.                                         $font_metrics[$alphabet{$symbol}]=array('start'=>$i);
  102.                                         $reading_symbol=true;
  103.                                         continue;
  104.                                 }
  105.  
  106.                                 if($reading_symbol && $transparent){
  107.                                         $font_metrics[$alphabet{$symbol}]['end']=$i;
  108.                                         $reading_symbol=false;
  109.                                         $symbol++;
  110.                                         continue;
  111.                                 }
  112.                         }
  113.  
  114.                         $img=imagecreatetruecolor($width, $height);
  115.                         imagealphablending($img, true);
  116.                         $white=imagecolorallocate($img, 255, 255, 255);
  117.                         $black=imagecolorallocate($img, 0, 0, 0);
  118.  
  119.                         imagefilledrectangle($img, 0, 0, $width-1, $height-1, $white);
  120.  
  121.                         // draw text
  122.                         $x=1;
  123.                         $odd=mt_rand(0,1);
  124.                         if($odd==0) $odd=-1;
  125.                         for($i=0;$i<$length;$i++){
  126.                                 $m=$font_metrics[$this->keystring{$i}];
  127.  
  128.                                 $y=(($i%2)*$fluctuation_amplitude - $fluctuation_amplitude/2)*$odd
  129.                                         + mt_rand(-round($fluctuation_amplitude/3), round($fluctuation_amplitude/3))
  130.                                         + ($height-$fontfile_height)/2;
  131.  
  132.                                 if($no_spaces){
  133.                                         $shift=0;
  134.                                         if($i>0){
  135.                                                 $shift=10000;
  136.                                                 for($sy=3;$sy<$fontfile_height-10;$sy+=1){
  137.                                                         for($sx=$m['start']-1;$sx<$m['end'];$sx+=1){
  138.                                                         $rgb=imagecolorat($font, $sx, $sy);
  139.                                                         $opacity=$rgb>>24;
  140.                                                                 if($opacity<127){
  141.                                                                         $left=$sx-$m['start']+$x;
  142.                                                                         $py=$sy+$y;
  143.                                                                         if($py>$height) break;
  144.                                                                         for($px=min($left,$width-1);$px>$left-200 && $px>=0;$px-=1){
  145.                                                                         $color=imagecolorat($img, $px, $py) & 0xff;
  146.                                                                                 if($color+$opacity<170){ // 170 - threshold
  147.                                                                                         if($shift>$left-$px){
  148.                                                                                                 $shift=$left-$px;
  149.                                                                                         }
  150.                                                                                         break;
  151.                                                                                 }
  152.                                                                         }
  153.                                                                         break;
  154.                                                                 }
  155.                                                         }
  156.                                                 }
  157.                                                 if($shift==10000){
  158.                                                         $shift=mt_rand(4,6);
  159.                                                 }
  160.  
  161.                                         }
  162.                                 }else{
  163.                                         $shift=1;
  164.                                 }
  165.                                 imagecopy($img, $font, $x-$shift, $y, $m['start'], 1, $m['end']-$m['start'], $fontfile_height);
  166.                                 $x+=$m['end']-$m['start']-$shift;
  167.                         }
  168.                 }while($x>=$width-10); // while not fit in canvas
  169.  
  170.                 //noise
  171.                 $white=imagecolorallocate($font, 255, 255, 255);
  172.                 $black=imagecolorallocate($font, 0, 0, 0);
  173.                 for($i=0;$i<(($height-30)*$x)*$white_noise_density;$i++){
  174.                         imagesetpixel($img, mt_rand(0, $x-1), mt_rand(10, $height-15), $white);
  175.                 }
  176.                 for($i=0;$i<(($height-30)*$x)*$black_noise_density;$i++){
  177.                         imagesetpixel($img, mt_rand(0, $x-1), mt_rand(10, $height-15), $black);
  178.                 }
  179.  
  180.                
  181.                 $center=$x/2;
  182.  
  183.                 // credits. To remove, see configuration file
  184.                 $img2=imagecreatetruecolor($width, $height+($show_credits?12:0));
  185.                 $foreground=imagecolorallocate($img2, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
  186.                 $background=imagecolorallocate($img2, $background_color[0], $background_color[1], $background_color[2]);
  187.                 imagefilledrectangle($img2, 0, 0, $width-1, $height-1, $background);           
  188.                 imagefilledrectangle($img2, 0, $height, $width-1, $height+12, $foreground);
  189.                 $credits=empty($credits)?$_SERVER['HTTP_HOST']:$credits;
  190.                 imagestring($img2, 2, $width/2-imagefontwidth(2)*strlen($credits)/2, $height-2, $credits, $background);
  191.  
  192.                 // periods
  193.                 $rand1=mt_rand(750000,1200000)/10000000;
  194.                 $rand2=mt_rand(750000,1200000)/10000000;
  195.                 $rand3=mt_rand(750000,1200000)/10000000;
  196.                 $rand4=mt_rand(750000,1200000)/10000000;
  197.                 // phases
  198.                 $rand5=mt_rand(0,31415926)/10000000;
  199.                 $rand6=mt_rand(0,31415926)/10000000;
  200.                 $rand7=mt_rand(0,31415926)/10000000;
  201.                 $rand8=mt_rand(0,31415926)/10000000;
  202.                 // amplitudes
  203.                 $rand9=mt_rand(330,420)/110;
  204.                 $rand10=mt_rand(330,450)/100;
  205.  
  206.                 //wave distortion
  207.  
  208.                 for($x=0;$x<$width;$x++){
  209.                         for($y=0;$y<$height;$y++){
  210.                                 $sx=$x+(sin($x*$rand1+$rand5)+sin($y*$rand3+$rand6))*$rand9-$width/2+$center+1;
  211.                                 $sy=$y+(sin($x*$rand2+$rand7)+sin($y*$rand4+$rand8))*$rand10;
  212.  
  213.                                 if($sx<0 || $sy<0 || $sx>=$width-1 || $sy>=$height-1){
  214.                                         continue;
  215.                                 }else{
  216.                                         $color=imagecolorat($img, $sx, $sy) & 0xFF;
  217.                                         $color_x=imagecolorat($img, $sx+1, $sy) & 0xFF;
  218.                                         $color_y=imagecolorat($img, $sx, $sy+1) & 0xFF;
  219.                                         $color_xy=imagecolorat($img, $sx+1, $sy+1) & 0xFF;
  220.                                 }
  221.  
  222.                                 if($color==255 && $color_x==255 && $color_y==255 && $color_xy==255){
  223.                                         continue;
  224.                                 }else if($color==0 && $color_x==0 && $color_y==0 && $color_xy==0){
  225.                                         $newred=$foreground_color[0];
  226.                                         $newgreen=$foreground_color[1];
  227.                                         $newblue=$foreground_color[2];
  228.                                 }else{
  229.                                         $frsx=$sx-floor($sx);
  230.                                         $frsy=$sy-floor($sy);
  231.                                         $frsx1=1-$frsx;
  232.                                         $frsy1=1-$frsy;
  233.  
  234.                                         $newcolor=(
  235.                                                 $color*$frsx1*$frsy1+
  236.                                                 $color_x*$frsx*$frsy1+
  237.                                                 $color_y*$frsx1*$frsy+
  238.                                                 $color_xy*$frsx*$frsy);
  239.  
  240.                                         if($newcolor>255) $newcolor=255;
  241.                                         $newcolor=$newcolor/255;
  242.                                         $newcolor0=1-$newcolor;
  243.  
  244.                                         $newred=$newcolor0*$foreground_color[0]+$newcolor*$background_color[0];
  245.                                         $newgreen=$newcolor0*$foreground_color[1]+$newcolor*$background_color[1];
  246.                                         $newblue=$newcolor0*$foreground_color[2]+$newcolor*$background_color[2];
  247.                                 }
  248.  
  249.                                 imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newred, $newgreen, $newblue));
  250.                         }
  251.                 }
  252.                
  253.                 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  254.                 header('Cache-Control: no-store, no-cache, must-revalidate');
  255.                 header('Cache-Control: post-check=0, pre-check=0', FALSE);
  256.                 header('Pragma: no-cache');
  257.                 if(function_exists("imagejpeg")){
  258.                         header("Content-Type: image/jpeg");
  259.                         imagejpeg($img2, null, $jpeg_quality);
  260.                 }else if(function_exists("imagegif")){
  261.                         header("Content-Type: image/gif");
  262.                         imagegif($img2);
  263.                 }else if(function_exists("imagepng")){
  264.                         header("Content-Type: image/x-png");
  265.                         imagepng($img2);
  266.                 }
  267.                
  268.         }
  269.  
  270.         // returns keystring
  271.         function getKeyString(){
  272.                 return $this->keystring;
  273.         }
  274. }
  275.  
  276. ?>


index.php
CODE (htmlphp):
скопировать код в буфер обмена
  1. <?php
  2.  
  3.  
  4. include('kcaptcha.php');
  5.  
  6.  
  7. $captcha = new KCAPTCHA();
  8.  
  9. ?>
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Хранение данных, их вывод и обработка »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB