Странный выпуск Password_Hash

1

Таким образом, я использую тот же самый сценарий, что и раньше, и по какой-то причине, когда я переезжаю в свой новый домен и хостинг у него возникают действительно странные проблемы, я создал пользователя и получил hm, чтобы попробовать войти в систему, он не работал для него Я получил новый хэш из случайного файла test.php с этим php:

<?php
/**
 * In this case, we want to increase the default cost for BCRYPT to 12.
 * Note that we also switched to BCRYPT, which will always be 60 characters.
 */
$options = [
    'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>

Затем он работал, он вошел в систему, и затем я попытался войти в свою основную учетную запись администратора и по какой-то причине теперь не работает, даже когда я пытаюсь переделать хэш 2 раза.

Я понятия не имею, что происходит, кто-то может просветить меня.

Вот код входа:

//If User Submits Form continue;
if(isset($_POST['username'])) {

    //If the captcha wasn't submitted;
    if(empty($_POST['g-recaptcha-response'])) {

        //And theres already a try with there IP;
        if($trycount != '0') {

            //Increment there try count and give a notification;
            updateTries(); ?>
            <script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php

        //If there isn't a try on there IP yet;
        } else {

            //Add one try and give a notification;
            addTry(); ?>
            <script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php

        }

    //If the captcha was submitted;
    } else {

        //Set captcha variable to the Submitted Captcha Response;
        $captcha=$_POST['g-recaptcha-response'];

        //Captcha Verification Url;
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';

        //JSON Encode the Captcha response and Site IP;
        $response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);

        //If the captcha wasn't verified;
        if($response['success'] == false) {

            //And theres already a try with there IP;
            if($trycount != '0') {

                //Increment there try count and give a notification;
                updateTries(); ?>
                <script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php

            //If there isn't a try on there IP yet;
            } else {

                //Add one try and give a notification;
                addTry(); ?>
                <script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php

            }

        //Otherwise if it was verified;
        } else {

            //Try log in with the given details;
            user_login($_POST['username'],$_POST['password']);

            //If logged in redirect and give a notification;        
            if(loggedin()) { ?>
                <script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
                <meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
            } else {

                //And theres already a try with there IP;
                if($trycount != '0') {

                    //Increment there try count and give a notification;
                    updateTries(); ?>
                    <script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php

                //If there isn't a try on there IP yet;
                } else {

                    //Add one try and give a notification;
                    addTry(); ?>
                    <script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php

                }

            }

        }

    }

}

Функция User_login:

//Create a new function named user_login;
function user_login($username = false, $password = false) {

    //Fetch for the username and password applied;
    $st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));

    //If a row was found continue
    if($st != 0) {

        $storedhash = $st[0]['password'];

        if (password_verify($password, $storedhash)) {

            //Set a new username session and set it the username;
            $_SESSION['username'] = $username;
            $_SESSION['email'] = $st[0]['email'];
            $_SESSION['image'] = $st[0]['image'];

            if($username == 'admin') {
                $_SESSION['role'] = 'admin';
            } else {
                $_SESSION['role'] = 'user';
            }

        }

    }

    //If no errors happened Make the $valid true;
    return true;

    $dontaddtry = true;

}

Функция Fetch:

//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {

    //Prepare The SQL Query;
    $query = Connect()->prepare($sql);

    //Execute Binded Query;
    $query->execute($bind);

    //While Fetching Results;
    while($result = $query->fetch(PDO::FETCH_ASSOC)) {

        //Add a row to the results respectiveley;
        $row[] = $result;

    }

    //If there are no rows;
    if(!empty($row)) {

        //Make it an object;
        $row = ($obj)? (object) $row : $row;
    } else {

        //Else row is false;
        $row = false;
    }

    //If no errors happened Make $row true;
    return $row;

}

Функция подключения:

//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {

    //Try execute the PHP with no errors;
    try {

        //Create a PDO Session;
        $con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

        //Session Attributes;
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    }

    //Catch all PDOException errors;
    catch (PDOException $e) {

        //If any errors print result;
        echo "<code><pre>".print_r($e)."</pre></code>";

        //Make the PDO session false;
        $con = false;
    }

    //If no errors happened Make the PDO session true;
    return $con;
}

PS Если вы хотите получить учетную запись, чтобы попробовать на моем сайте, дайте мне знать, и я делаю временную учетную запись.

  • 0
    Правильный ли хеш в базе данных или это пустая строка? Какой тип столбца используется для хранения хеша?
  • 0
    Это правильно, конечно, и это Varchar (60).
Показать ещё 1 комментарий
Теги:
php-password-hash

1 ответ

0

Убедитесь, что ваш php-версия вашего нового хостинга. password_hash требуется как минимум для PHP 5.5.0.

Вы можете проверить свою текущую версию PHP через следующий код.

<?php
    echo 'Current PHP version: ' . phpversion();
?>
  • 0
    Да, ofc im 5.6 в противном случае это не сработает.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню