Вывести Captcha php в классе

191
14 мая 2018, 19:10

Создал Captcha, как описано здесь в отдульном файле php и она выводиться, все меняется, но задача вывести captcha в классе, но что-то не получается. Вот пример рабочей Captcha не в классе, а в файле captcha.php.

<?php
$captcha_length = 6;
$image = imagecreatetruecolor ( 200, 75 );
$back_color = @ImageColorAllocate ( $image, 255, 255, 255 );
$code = "";
$inputCode = $_POST['captcha'];
for($i = 0; $i < $captcha_length; $i ++) {
    $x_axis = 20 + ($i * 20);
    $y_axis = 50 + rand ( 0, 7 );
    $color1 = rand ( 001, 150 );
    $color2 = rand ( 001, 150 );
    $color3 = rand ( 001, 150 );
    $txt_color [$i] = ImageColorAllocate ( $image, $color1, $color2, $color3 );
    $size = rand ( 20, 30 );
    $angle = rand ( -15, 15 );
    $number = function ($len=1) {
        $s = "";
        $b="QWERTYUPASDFGHJKLZXCVBNMqwertyuopasdfghjkzxcvbnm123456789";
        while($len-->0)  {
            $s.=$b[mt_rand(0,strlen($b))];
        }
        return "$s";
    };
    $t = $number();
    $code .= "$t";
    imagettftext ( $image, $size, $angle, $x_axis, $y_axis, $txt_color[$i], "C:\OSPanel\domains\kultprosvet\arial.ttf", $t);
}
session_start();
$_SESSION ['captcha'] = $code;
header ( "Cache-Control: no-cache" );
header ( "Content-type: image/jpg" );
imagejpeg ( $image);
exit ();

Вот файл index.html где Captcha выводится

<form id = "form">
            <input id = "name" type = "text" minlength="2" placeholder="Ваше имя" name = "name" required>
            <input id = "s_name" type = "text" placeholder="Ваша фамилия" name = "s_name" required>
            <input id = "email" type = "text" placeholder="email" name = "email" required>
            <select id = "ticket" required name = "ticket">
                <option>free</option>
                <option>standart</option>
                <option>premium</option>
            </select>
            <img alt="" id="captcha" src="captcha.php" />
            <span onclick="document.getElementById('captcha').src=document.getElementById( 'captcha').src + '?' + Math.random();">обновить код</span>
            <input type="text" maxlength="<?=$captcha_length;?>" style="text-align: center;" autocomplete="off" name="captcha" value=""/>
            <input id = "submit" type = "submit">
        </form>

Задача создать такую же Captcha но все должно быть в классе, вот пример того,что я пытася сделать в классе Captcha.php

<?php
class Captcha
{
    public $captcha_length;
    public $image;
    public $back_color;
    public $code;
    public $inputCode;
    function __construct(){
        parent::__construct();
        $this->captcha_length = 6;
        $this->image =  imagecreatetruecolor (200, 75);
        $this->back_color = @ImageColorAllocate ($this->image, 255, 255, 255);
        $this->code = "";
        $this->inputCode = $_POST['captcha'];
    }
    function createCaptcha() {
        for ($i = 0;
             $i < $this->captcha_length;
             $i ++)
        {
            $x_axis = 20 + ($i * 20);
            $y_axis = 50 + rand (0, 7);
            $color1 = rand (001, 150);
            $color2 = rand (001, 150);
            $color3 = rand (001, 150);
            $txt_color [$i] = ImageColorAllocate ($this->image, $color1, $color2, $color3);
            $size = rand (20, 30);
            $angle = rand (-15, 15);
            $number = function ($len = 1)
            {
                $s = "";
                $b = "QWERTYUPASDFGHJKLZXCVBNMqwertyuopasdfghjkzxcvbnm123456789";
                while ($len-->0) {
                    $s .= $b[mt_rand(0, strlen($b))];
                }
                return "$s";
            };
            $t = $number();
            $this->code .= "$t";
            imagettftext ($this->image, $size, $angle, $x_axis, $y_axis, $txt_color[$i], "C:\OSPanel\domains\kultprosvet\arial.ttf", $t);
        }
        session_start();
        $_SESSION ['captcha'] = $this->code;
        header("Cache-Control: no-cache");
        header("Content-type: image/jpg");
        imagejpeg($this->image);
        exit ();
    }
}

В файле configCaptha.php мы инициализируем класс и методы класса. Вот код

<?php
$captcha = new Captcha();
$captcha->createCaptcha();

ну и в форме html все остается по прежнему, кроме того, что картинка выводится уже вот так <img alt="" id="captcha" src="configCaptha.php" />

Подтожу: если выводить Captcha в как в файле captcha.php, то все работает, но сделать Captcha через класс никак не могу. Где я ошибся? Спасибо

READ ALSO
Конвертация gif в mp4 | webm

Конвертация gif в mp4 | webm

Существуют ли какие-то библиотеки для конвертации "на лету" получаемых gif файлов? Или может какие-то уже готовые решения

192
Запустить команду через n-ное время

Запустить команду через n-ное время

Реализовал у себя на сайте алгоритм выполнения снапшотовРаботает следующим образом: при запросе робота одной из поисковых систем алгоритм...

222
Повторяющий html при обработке данных

Повторяющий html при обработке данных

Вот, есть такой javascript код:

188
Вывод данных из БД с сравнением PHP и MySQL

Вывод данных из БД с сравнением PHP и MySQL

Помогите вывести значения из таблицыперед этим сравнив их

203