Для отправки формы требуется дважды попытаться отправить информацию в БД - PullRequest
0 голосов
/ 21 октября 2019

Я новичок в PHP и работаю над системой входа в систему для своих мастеров, и у меня возникла следующая проблема. Я создал систему классов для работы с моим кодом и повторного его использования для различных нужд, затем я создал формы (регистрация, логин, пароль изменения, обновление, ...), проблема в том, что в любой форме, когда я пытаюсьотправить информацию, она будет отправлена ​​не в первый раз, а во второй, все отлично работает (проверка и создание пользователя, вход в систему и т. д.). У меня пустое действие в формах, я попытался установить действие на той же странице, но с тем же результатом. Я знаю, что это может сделать меня из-за того, что в первой попытке URL-адрес пуст, и для продолжения нужна вторая, но я не знаю, как это сделать. Вот код моей регистрационной формы:

<!-- -------------------- REGISTER.PHP -------------------- -->

<?php

require_once 'core/init.php'; // Check name of the initialization file

include 'includes/heade&header.php';      // HEAD and HEADER of the site

if(Input::exists()) {
    if(Token::check(Input::get('token'))) {

        $validate = new Validate();
        $validation = $validate -> check($_POST, array(
            'username' => array(            // Check name of input
                'required' => true,         // Add conditions to the inputs
                'min' => 2,
                'max' => 20,
                'unique' => 'users'
            ),
            'firstname' => array(                // Check name of input
                'required' => false,         // Add conditions to the inputs
                'min' => 2,
                'max' => 50,
                'text' => true
            ),
            'lastname' => array(        // Check name of input
                'required' => false,        // Add conditions to the inputs
                'min' => 2,
                'max' => 50,
                'text' => true
            ),
            'email' => array(       // Check name of input
                'required' => true,     // Add conditions to the inputs
                'email' => true
            ),
            'password' => array(            // Check name of input
                'required' => true,         // Add conditions to the inputs
                'min' => 6,
                'max' => 12,
                'password_NUM' => true,
                'password_CAP' => true,
                'password_LOW' => true,
                'password_S-CHAR' => true
            ),
            'password_again' => array(      // Check name of input
                'required' => true,         // Add conditions to the inputs
                'matches' => 'password'
            )

            // If there are more inputs in the form extend to needs

        ));

        if($validation -> passed()) {

            $user = new User();

            $salt = Hash::salt(32);

            try {
                $user -> create(array(
                    'username' => Input::get('username'),
                    'firstname' => Input::get('firstname'),
                    'lastname' => Input::get('lastname'),
                    'email' => Input::get('email'),
                    'password' => Hash::make(Input::get('password'), $salt),
                    'salt' => $salt,
                    'joined' => date('Y-m-d H:i:s'),
                    'group' => 1
                ));

                Session::flash('home', 'You have been registered and can now log in!');
                Redirect::to('index.php');

                // Add email of confirmation to complete the app

            } catch(Exception $e) {
                die($e -> getMessage());
            }
        } else {
            foreach($validation -> errors() as $error) {
                echo $error, '<br/>';
            }
        }
    }
}

?>
<form action="" method="post">

    <div class="field">
        <label for="username">Username</label>
        <input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
    </div>

    <div class="field">
        <label for="firstname">First name</label>
        <input type="text" name="firstname" value="<?php echo escape(Input::get('firstname')); ?>" id="firstname">
    </div>

    <div class="field">
        <label for="lastname">Lastname</label>
        <input type="text" name="lastname" value="<?php echo escape(Input::get('lastname')); ?>" id="lastname">
    </div>

    <div class="field">
        <label for="email">E-mail</label>
        <input type="text" name="email" value="<?php echo escape(Input::get('email')); ?>" id="email">
    </div>

    <div class="field">
        <label for="password">Password</label>
        <input type="password" name="password" id="password">
    </div>

    <div class="field">
        <label for="password_again">Enter your password again</label>
        <input type="password" name="password_again" id="password_again">
    </div>

    <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">

    <input type="submit" value="Register">

</form>

Это все одна страница.

Спасибо за вашу помощь и терпение.

1 Ответ

0 голосов
/ 21 октября 2019

почему бы вам не разбить его на 2 файла?

  • 1 файл формы file_form.php
<form action="file_process.php" method="post">
    <div class="field">
        <label for="username">Username</label>
        <input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
    </div>

    <div class="field">
        <label for="firstname">First name</label>
        <input type="text" name="firstname" value="<?php echo escape(Input::get('firstname')); ?>" id="firstname">
    </div>

    <div class="field">
        <label for="lastname">Lastname</label>
        <input type="text" name="lastname" value="<?php echo escape(Input::get('lastname')); ?>" id="lastname">
    </div>

    <div class="field">
        <label for="email">E-mail</label>
        <input type="text" name="email" value="<?php echo escape(Input::get('email')); ?>" id="email">
    </div>

    <div class="field">
        <label for="password">Password</label>
        <input type="password" name="password" id="password">
    </div>

    <div class="field">
        <label for="password_again">Enter your password again</label>
        <input type="password" name="password_again" id="password_again">
    </div>
    <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
    <input type="submit" value="Register">
</form>
  • 1 файловый процесс file_process.php
<?php

    if(Input::exists()) {
        if(Token::check(Input::get('token'))) {

            $validate = new Validate();
            $validation = $validate -> check($_POST, array(
                'username' => array(            // Check name of input
                'required' => true,         // Add conditions to the inputs
                'min' => 2,
                'max' => 20,
                'unique' => 'users'
            ),
            'firstname' => array(                // Check name of input
                'required' => false,         // Add conditions to the inputs
                'min' => 2,
                'max' => 50,
                'text' => true
            ),
            'lastname' => array(        // Check name of input
                'required' => false,        // Add conditions to the inputs
                'min' => 2,
                'max' => 50,
                'text' => true
            ),
            'email' => array(       // Check name of input
                'required' => true,     // Add conditions to the inputs
                'email' => true
            ),
            'password' => array(            // Check name of input
                'required' => true,         // Add conditions to the inputs
                'min' => 6,
                'max' => 12,
                'password_NUM' => true,
                'password_CAP' => true,
                'password_LOW' => true,
                'password_S-CHAR' => true
            ),
            'password_again' => array(      // Check name of input
                'required' => true,         // Add conditions to the inputs
                'matches' => 'password'
            )

            // If there are more inputs in the form extend to needs

            ));

            if($validation -> passed()) {

                $user = new User();

                $salt = Hash::salt(32);

                try {
                    $user -> create(array(
                        'username' => Input::get('username'),
                        'firstname' => Input::get('firstname'),
                        'lastname' => Input::get('lastname'),
                        'email' => Input::get('email'),
                        'password' => Hash::make(Input::get('password'), $salt),
                        'salt' => $salt,
                        'joined' => date('Y-m-d H:i:s'),
                        'group' => 1
                    ));

                    Session::flash('home', 'You have been registered and can now log in!');
                    Redirect::to('index.php');

                    // Add email of confirmation to complete the app

                } catch(Exception $e) {
                    die($e -> getMessage());
                }
            } else {
                foreach($validation -> errors() as $error) {
                    echo $error, '<br/>';
                }
            }
        }
    }

?>

...