• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Solved [Znoteacc] Checking is everything is correctly before submitting the form while create account.

johnsamir

Advanced OT User
Joined
Oct 13, 2009
Messages
1,094
Solutions
6
Reaction score
192
Location
Nowhere
Hello as tittle says.

I'm trying to check if everything is okey by this i mean if account has the desired parameters if its on use or not and so on...
in register.php at the registration filling form part i've made this
Lua:
<!-- <form action="" method="post"> -->
    <form id="register-form" action="" method="post">
    <ul>
        <li>
            <b>Account:<br></b>
            <input type="text" name="username" id="username" oninput="checkUsername()">
            <span id="username-error" style="color:red;"></span>
            <span id="username-success" style="color:green;"></span>
        </li>
        <li>
            <b>Password:<br></b>
            <input type="password" name="password" id="password" oninput="checkPasswordMatch()">
        </li>
        <li>
            <b>Password again:<br></b>
            <input type="password" name="password_again" id="password_again" oninput="checkPasswordMatch()">
            <span id="password-error" style="color:red;"></span>
            <span id="password-success" style="color:green;"></span>
        </li>
        <li>
            <b>Email:<br></b>
            <input type="text" name="email" id="email" oninput="checkEmail()">
            <span id="email-error" style="color:red;"></span>
            <span id="email-success" style="color:green;"></span>
        </li>
            <li>
                <b>Country:<br></b>
                <select name="flag">
                    <option value="">(Please choose)</option>
                    <?php
                    foreach(array('pl', 'se', 'br', 'us', 'gb', ) as $c)
                        echo '<option value="' . $c . '">' . $config['countries'][$c] . '</option>';

                        echo '<option value="">----------</option>';
                        foreach($config['countries'] as $code => $c)
                            echo '<option value="' . $code . '">' . $c . '</option>';
                    ?>
                </select>
            </li>
            <?php
            if ($config['use_captcha']) {
                ?>
                <li>
                     <div class="g-recaptcha" data-sitekey="<?php echo $config['captcha_site_key']; ?>"></div>
                </li>
                <?php
            }
            ?>
            <li>
                <h2>Server Rules</h2>
                <p>The golden rule: Have fun.</p>
                <p>If you get pwn3d, don't hate the game.</p>
                <p>No <a href='https://en.wikipedia.org/wiki/Cheating_in_video_games' target="_blank">cheating</a> allowed.</p>
                <p>No <a href='https://en.wikipedia.org/wiki/Video_game_bot' target="_blank">botting</a> allowed.</p>
                <p>The staff can delete, ban, do whatever they want with your account and your <br>
                    submitted information. (Including exposing and logging your IP).</p>
            </li>
            <li>
                Do you agree to follow the server rules?<br>
                <select name="selected">
                  <option value="0">Umh...</option>
                  <option value="1">Yes.</option>
                  <option value="2">No.</option>
                </select>
            </li>
            <?php
                /* Form file */
                Token::create();
            ?>
            <li>
                    <input type="submit" value="Create Account" div class="BigButton btn" style="margin: 0 5px;display: inline-block;background-image:url(layout/tibia_img/sbutton.gif)">
                <!-- <input type="submit" value="Create Account"> -->
            </li>
        </ul>
    </form>
     </tr>
at the bottom of the same file i've added this
Code:
<script>
function checkUsername() {
    const username = document.getElementById('username').value;
    const usernameError = document.getElementById('username-error');
    const usernameSuccess = document.getElementById('username-success');

    usernameError.textContent = '';
    usernameSuccess.textContent = '';

    if (username.length === 0) {
        usernameError.textContent = 'Username is required.';
        return;
    }

    if (!/^[0-9]+$/.test(username)) {
        usernameError.textContent = 'Username can only contain numbers.';
        return;
    }

    if (username.length !== 8) {
        usernameError.textContent = 'Username must be exactly 8 digits long.';
        return;
    }

    fetch('check_username.php?username=' + encodeURIComponent(username))
        .then(response => response.json())
        .then(data => {
            if (data.exists) {
                usernameError.textContent = 'Username is already in use.';
            } else {
                usernameSuccess.textContent = 'Username is available.';
            }
        })
        .catch(error => {
            usernameError.textContent = 'Error checking username.';
        });
}

function checkPasswordMatch() {
    const password = document.getElementById('password').value;
    const passwordAgain = document.getElementById('password_again').value;
    const passwordError = document.getElementById('password-error');
    const passwordSuccess = document.getElementById('password-success');

    passwordError.textContent = '';
    passwordSuccess.textContent = '';

    if (password.length < 6 || password.length > 12) {
        passwordError.textContent = 'Password must be between 6 and 12 characters.';
        return;
    }

    if (password !== passwordAgain) {
        passwordError.textContent = 'Passwords do not match.';
    } else {
        passwordSuccess.textContent = 'Passwords match.';
    }
}

function checkEmail() {
    const email = document.getElementById('email').value;
    const emailError = document.getElementById('email-error');
    const emailSuccess = document.getElementById('email-success');

    emailError.textContent = '';
    emailSuccess.textContent = '';

    if (email.length === 0) {
        emailError.textContent = 'Email is required.';
        return;
    }

    if (!/\S+@\S+\.\S+/.test(email)) {
        emailError.textContent = 'A valid email address is required.';
        return;
    }

    fetch('check_email.php?email=' + encodeURIComponent(email))
        .then(response => response.json())
        .then(data => {
            if (data.exists) {
                emailError.textContent = 'Email is already in use.';
            } else {
                emailSuccess.textContent = 'Email is available.';
            }
        })
        .catch(error => {
            emailError.textContent = 'Error checking email.';
        });
}
</script>
in the same folder i've added too
username_check.php
Code:
<?php
require_once 'engine/init.php';
header('Content-Type: application/json');

if (isset($_GET['username'])) {
    $username = $_GET['username'];
    $response = ['exists' => user_exist($username)];
    echo json_encode($response);
    exit;
}
?>
and email_check.php
Code:
<?php
require_once 'engine/init.php';
header('Content-Type: application/json');

if (isset($_GET['email'])) {
    $email = $_GET['email'];
    $response = ['exists' => user_email_exist($email)];
    echo json_encode($response);
}
?>
its mostly working but when i use a password that is already in use i get this
Code:
Username must be exactly 8 digits long.
and if i use one that is not in use get the error checking username
can somebody lend me a hdn with this?
if this something is already in use as email i get this
Lua:
Error checking email.
 
Last edited:
in the same folder i've added too
username_check.php
and email_check.php
JavaScript:
fetch('check_username.php?username=' + encodeURIComponent(username))
...
fetch('check_email.php?email=' + encodeURIComponent(email))
Your php files do not match what are being called...
Rename them to check_username.php and check_email.php or change the URL paths in the code...
 
Edit talking about for example email checking

related to email in the filling form it look like this <
Code:
!-- <form action="" method="post"> -->
    <form id="register-form" action="" method="post">
    <ul>
        <li>
            <b>Account:<br></b>
            <input type="text" name="username" id="username" oninput="checkUsername()">
            <span id="username-error" style="color:red;"></span>
            <span id="username-success" style="color:green;"></span>
        </li>
        <li>
            <b>Password:<br></b>
            <input type="password" name="password" id="password" oninput="checkPasswordMatch()">
        </li>
        <li>
            <b>Password again:<br></b>
            <input type="password" name="password_again" id="password_again" oninput="checkPasswordMatch()">
            <span id="password-error" style="color:red;"></span>
            <span id="password-success" style="color:green;"></span>
        </li>
        <form id="register-form" action="" method="post">
    <ul>
        <li>
            <b>Email:<br></b>
            <input type="text" id="email" name="email" oninput="checkEmail()">
            <span id="email-error" style="color: red;"></span>
            <span id="email-success" style="color: green;"></span>
        </li>
        <!-- Other form fields -->
    </ul>
</form>
        <li>
            <li>
                <b>Country:<br></b>
                <select name="flag">
in the same file register.php the script
Code:
<script>
function checkUsername() {
    const username = document.getElementById('username').value;
    const usernameError = document.getElementById('username-error');
    const usernameSuccess = document.getElementById('username-success');


    // Clear previous messages
    usernameError.textContent = '';
    usernameSuccess.textContent = '';


    if (username.length === 0) {
        usernameError.textContent = 'Username is required.';
        return;
    }


    fetch('check_username.php?username=' + encodeURIComponent(username))
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                usernameError.textContent = data.error;
            } else if (data.exists) {
                usernameError.textContent = 'Username is already in use.';
            } else {
                usernameSuccess.textContent = 'Username is available.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            usernameError.textContent = 'Error checking username.';
        });
}


function checkEmail() {
    const email = document.getElementById('email').value;
    const emailError = document.getElementById('email-error');
    const emailSuccess = document.getElementById('email-success');


    emailError.textContent = ''; // Clear any previous error message
    emailSuccess.textContent = ''; // Clear any previous success message


    if (email.length === 0) {
        emailError.textContent = 'Email is required.';
        return;
    }


    fetch('check_email.php?email=' + encodeURIComponent(email))
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                emailError.textContent = data.error;
            } else if (data.exists) {
                emailError.textContent = 'Email is already in use.';
            } else {
                emailSuccess.textContent = 'Email is available.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            emailError.textContent = 'Error checking email.';
        });
}
</script>
check email.php
Code:
<?php
require_once 'engine/init.php';


header('Content-Type: application/json');


if (isset($_GET['email'])) {
    $email = $_GET['email'];


    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $exists = user_email_exist($email);


        echo json_encode(['exists' => $exists]);
    } else {
        echo json_encode(['error' => 'Invalid email format']);
    }
} else {
    echo json_encode(['error' => 'Email not provided']);
}
Lua:
?> init.php (full) <?php
if (version_compare(phpversion(), '5.6', '<')) die('PHP version 5.6 or higher is required.');


// Database connection settings
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xxxx";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


require_once 'engine/function/users.php'; // Ensure the path is correct


$l_time = microtime(true);
$l_start = $l_time;


function elapsedTime($l_start = false, $l_time = false) {
    if ($l_start === false) global $l_start;
    if ($l_time === false) global $l_time;


    $l_time = explode(' ', microtime());
    $l_finish = $l_time[1] + $l_time[0];
    return round(($l_finish - $l_start), 4);
}


$time = time();
$version = '1.6';


$aacQueries = 0;
$accQueriesData = array();


session_start();
ob_start();
require_once 'config.php';
$sessionPrefix = $config['session_prefix'];
if ($config['paypal']['enabled'] || $config['use_captcha']) {
    $curlcheck = extension_loaded('curl');
    if (!$curlcheck) die("php cURL is not enabled. It is required to for paypal or captcha services.<br>1. Find your php.ini file.<br>2. Uncomment extension=php_curl<br>Restart web server.<br><br><b>If you don't want this then disable paypal & use_captcha in config.php.</b>");
}
if ($config['use_captcha'] && !extension_loaded('openssl')) {
    die("php openSSL is not enabled. It is required to for captcha services.<br>1. Find your php.ini file.<br>2. Uncomment extension=php_openssl<br>Restart web server.<br><br><b>If you don't want this then disable use_captcha in config.php.</b>");
}


// References ( & ) works as an alias for a variable,
// they point to the same memmory, instead of duplicating it.
if (!isset($config['TFSVersion'])) $config['TFSVersion'] = &$config['ServerEngine'];
if (!isset($config['ServerEngine'])) $config['ServerEngine'] = &$config['TFSVersion'];


require_once 'database/connect.php';
require_once 'function/general.php';
require_once 'function/users.php';
require_once 'function/cache.php';
require_once 'function/mail.php';
require_once 'function/token.php';
require_once 'function/itemparser/itemlistparser.php';


if (isset($_SESSION['token'])) {
    $_SESSION['old_token'] = $_SESSION['token'];
}
Token::generate();


$tfs_10_hasPremDays = true; // https://github.com/otland/forgottenserver/pull/2813


if (user_logged_in() === true) {
    $session_user_id = getSession('user_id');
    if ($config['ServerEngine'] !== 'OTHIRE') {
        if ($config['ServerEngine'] == 'TFS_10') {
            $hasPremDays = mysql_select_single("SHOW COLUMNS from `accounts` WHERE `Field` = 'premium_ends_at'");
            if ($hasPremDays === false) {
                $tfs_10_hasPremDays = false;
                $user_data = user_data($session_user_id, 'id', 'name', 'password', 'email', 'premium_ends_at');
                $user_data['premium_ends_at'] = ($user_data['premium_ends_at'] - time() > 0) ? floor(($user_data['premium_ends_at'] - time()) / 86400) : 0;
            } else {
                $user_data = user_data($session_user_id, 'id', 'name', 'password', 'email', 'premium_ends_at');
            }
        } else {
            $user_data = user_data($session_user_id, 'id', 'name', 'password', 'email', 'premium_ends_at');
        }
    } else
        $user_data = user_data($session_user_id, 'id', 'password', 'email', 'premend');
    $user_znote_data = user_znote_account_data($session_user_id, 'ip', 'created', 'points', 'cooldown', 'flag' ,'active_email');
}
$errors = array();
// Log IP
if ($config['log_ip']) {
    $visitor_config = $config['ip_security'];


    $flush = $config['flush_ip_logs'];
    if ($flush != false) {
        $timef = $time - $flush;
        if (getCache() < $timef) {
            $timef = $time - $visitor_config['time_period'];
            mysql_delete("DELETE FROM znote_visitors_details WHERE time <= '$timef'");
            setCache($time);
        }
    }


    $visitor_data = znote_visitors_get_data();


    znote_visitor_set_data($visitor_data); // update or insert data
    znote_visitor_insert_detailed_data(0); // detailed data


    $visitor_detailed = znote_visitors_get_detailed_data($visitor_config['time_period']);


    // max activity
    $v_activity = 0;
    $v_register = 0;
    $v_highscore = 0;
    $v_c_char = 0;
    $v_s_char = 0;
    $v_form = 0;
    foreach ((array)$visitor_detailed as $v_d) {
        // Activity
        if ($v_d['ip'] == getIPLong()) {
            // count each type of visit
            switch ($v_d['type']) {
                case 0: // max activity
                    $v_activity++;
                break;


                case 1: // account registered
                    $v_register++;
                    $v_form++;
                break;


                case 2: // character creations
                    $v_c_char++;
                    $v_form++;
                break;


                case 3: // Highscore fetched
                    $v_highscore++;
                    $v_form++;
                break;


                case 4: // character searched
                    $v_s_char++;
                    $v_form++;
                break;


                case 5: // Other forms (login.?)
                    $v_form++;
                break;
            }


        }
    }


    // Deny access if activity is too high
    if ($v_activity > $visitor_config['max_activity']) die("Chill down. Your web activity is too big. max_activity");
    if ($v_register > $visitor_config['max_account']) die("Chill down. You can't create multiple accounts that fast. max_account");
    if ($v_c_char > $visitor_config['max_character']) die("Chill down. Your web activity is too big. max_character");
    if ($v_form > $visitor_config['max_post']) die("Chill down. Your web activity is too big. max_post");


    //var_dump($v_activity, $v_register, $v_highscore, $v_c_char, $v_s_char, $v_form);
    //echo ' <--- IP logging activity past 10 seconds.';
}


// Sub page override system
$filename = explode('/', $_SERVER['SCRIPT_NAME']);
$filename = $filename[count($filename) - 1];
$page_filename = str_replace('.php', '', $filename);
if ($config['allowSubPages']) {
    require_once 'layout/sub.php';
    if (isset($subpages) && !empty($subpages)) {
        foreach ($subpages as $page) {
            if ($page['override'] && $page['file'] === $filename) {
                require_once 'layout/overall/header.php';
                require_once 'layout/sub/'.$page['file'];
                require_once 'layout/overall/footer.php';
                exit;
            }
        }
    } else {
        ?>
        <div style="background-color: white; padding: 20px; width: 100%; float:left;">
            <h2 style="color: black;">Old layout!</h2>
            <p style="color: black;">The layout is running an outdated sub system which is not compatible with this version of Znote AAC.</p>
            <p style="color: black;">The file /layout/sub.php is outdated.
            <br>Please update it to look like <a style="color: orange;" target="_BLANK" href="https://github.com/Znote/ZnoteAAC/blob/master/layout/sub.php">THIS.</a>
            </p>
        </div>
        <?php
    }
}
?>
not getting errors, loading in website or visible errors
but does not matters if the email its in use or not i get this message Error checking email.
 
As it is logged, here:
Code:
console.error('Error:', error);

You should see an error in your browser console. What does it say?
 
As it is logged, here:
Code:
console.error('Error:', error);

You should see an error in your browser console. What does it say?
Error checking username. the same for email is because is not accessing to database ? don't want to check if they exists or not just want to review if they are already in use in the database
 
Error checking username. the same for email is because is not accessing to database ? don't want to check if they exists or not just want to review if they are already in use in the database
When the error happens, right click anywhere on the page, click Inspect, then click console on the top (There are various ways to get to the same place).

Post anything that is logged in the console here.
 
right i think i found it
1.png
have updated checkemail function
Lua:
function checkUsername() {
    const username = document.getElementById('username').value;
    const usernameError = document.getElementById('username-error');
    const usernameSuccess = document.getElementById('username-success');

    // Clear previous messages
    usernameError.textContent = '';
    usernameSuccess.textContent = '';

    if (username.length === 0) {
        usernameError.textContent = 'Username is required.';
        return;
    }

    console.log('Checking username:', username); // Debugging: Log username

    fetch('layout/sub/check_username.php?username=' + encodeURIComponent(username))
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Response:', data); // Debugging: Log response data
            if (data.exists) {
                usernameError.textContent = 'Username is already in use.';
            } else {
                usernameSuccess.textContent = 'Username is available.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            usernameError.textContent = 'Error checking username.';
        });
}

function checkEmail() {
    const email = document.getElementById('email').value;
    const emailError = document.getElementById('email-error');
    const emailSuccess = document.getElementById('email-success');

    // Clear any previous error or success messages
    emailError.textContent = '';
    emailSuccess.textContent = '';

    if (email.length === 0) {
        emailError.textContent = 'Email is required.';
        return;
    }

    fetch('layout/sub/check_email.php?email=' + encodeURIComponent(email))
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Response:', data); // Debugging: Log response data
            if (data.error) {
                emailError.textContent = data.error;
            } else if (data.exists !== undefined) {
                if (data.exists) {
                    emailError.textContent = 'Email is already in use.';
                } else {
                    emailSuccess.textContent = 'Email is available.';
                }
            } else {
                emailError.textContent = 'Unexpected response format.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            emailError.textContent = 'Error checking email.';
        });
}
Post automatically merged:

edit i went to via browser and its giving me the value
 
Last edited:
right i think i found it
View attachment 84824
have updated checkemail function
Lua:
function checkUsername() {
    const username = document.getElementById('username').value;
    const usernameError = document.getElementById('username-error');
    const usernameSuccess = document.getElementById('username-success');

    // Clear previous messages
    usernameError.textContent = '';
    usernameSuccess.textContent = '';

    if (username.length === 0) {
        usernameError.textContent = 'Username is required.';
        return;
    }

    console.log('Checking username:', username); // Debugging: Log username

    fetch('layout/sub/check_username.php?username=' + encodeURIComponent(username))
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Response:', data); // Debugging: Log response data
            if (data.exists) {
                usernameError.textContent = 'Username is already in use.';
            } else {
                usernameSuccess.textContent = 'Username is available.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            usernameError.textContent = 'Error checking username.';
        });
}

function checkEmail() {
    const email = document.getElementById('email').value;
    const emailError = document.getElementById('email-error');
    const emailSuccess = document.getElementById('email-success');

    // Clear any previous error or success messages
    emailError.textContent = '';
    emailSuccess.textContent = '';

    if (email.length === 0) {
        emailError.textContent = 'Email is required.';
        return;
    }

    fetch('layout/sub/check_email.php?email=' + encodeURIComponent(email))
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Response:', data); // Debugging: Log response data
            if (data.error) {
                emailError.textContent = data.error;
            } else if (data.exists !== undefined) {
                if (data.exists) {
                    emailError.textContent = 'Email is already in use.';
                } else {
                    emailSuccess.textContent = 'Email is available.';
                }
            } else {
                emailError.textContent = 'Unexpected response format.';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            emailError.textContent = 'Error checking email.';
        });
}
Post automatically merged:

edit i went to via browser and its giving me the value
Looks like a PHP error, which it's trying to deserialize JSON, therefore throwing an error. You need to log the response before its deserialized.

After this line:
JavaScript:
.then(response => {
add:
JavaScript:
console.log('Response:', response);
 
Last edited:
added found out that maybe something missing
Post automatically merged:

Solved had to add a lot of missing libraries like almost 6 they are shown in the picture above also
had to change the way that libraries were load like for example in this way
Code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../engine/init.php';
require_once '../../engine/function/users.php';
after that i removed the errors and was possible to load or handle everything properly


1716336917386.png
 

Attachments

Last edited:
It's because you put the check_username and check_email scripts in layout/subs/, therefore to include the init.php, you had to traverse back to the root directory first (adding ../../ before engine/init.php). If you kept them in the root directory it would have worked. Not sure why you had to include the users.php, this should already be called in init.php, but hey...as long as it works đź‘Ť
 
Back
Top