doutu6616 2018-06-02 14:48
浏览 51

如果用户名包含数字,则不保存PHP用户名会话变量

I searched for this question but couldn't find it.

I have made a create user page that will allow the user to create an account on my page using a username. Usernames can be any combination of letters and numbers. When they create the user, it is supposed to call the same page, then redirect the user to the main page when it sees that the session variable is now set.

When I create a user with only letters in the username, it works fine and redirects them to the index page. However, when I create a user such as "student1" it will not set the session variable and therefore not redirect them.

You can try it yourself at http://collinmath.com/accounts/create.php to see what I mean. (Just don't use real info since I haven't set up the SSL yet)

<?php

// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
    // Set variables equal to POST data
    $login_name = $_POST['username'];
    $first_name = $_POST['firstname'];
    $last_name = $_POST['lastname'];
    $email = $_POST['email'];
    $role = $_POST['role'];
    $pwd1 = $_POST['password_1'];
    $pwd2 = $_POST['password_2'];
    register();
}

// Register function will check the input and add the user if
// the input is accepted
function register() {

global $login_name;
global $first_name;
global $last_name;
global $email;
global $role;
global $errors;
global $connection;
global $pwd1;
global $pwd2;
global $hostname;
global $username;
global $password;
global $dbname;

// Connect to database
$connection = mysqli_connect($hostname, $username, $password);
mysqli_select_db($connection, $dbname);

// Check that username contains only letters and number
if (preg_match('/[^A-Za-z0-9]/', $login_name)) {
    array_push($errors, "Username must contain only letters and/or numbers");
} else {
    $login_name = strtolower($login_name);
}

// Sanitize SQL data
$first_name = mysqli_real_escape_string($connection, $first_name);
$last_name = mysqli_real_escape_string($connection, $last_name);

// Validate registration input and generate error log if there are issues

    // Check if username is taken or empty
    if (strlen($login_name) > 4) {
        $query = "SELECT `User_Login` AS `Login` FROM `CMP_Users` WHERE `User_Login`=?";

        $mysqli = new mysqli($hostname, $username, $password, $dbname);
        $mysqli->set_charset("utf8");
        $stmt = $mysqli->prepare($query);
        $stmt->bind_param("s", $login_name);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        if ($row[Login]) {
            array_push($errors, "That username is taken");
        } 
    } else {
        array_push($errors, "Username must be at least 5 characters long");
    };

    if (strlen($login_name) > 16) {
        array_push($errors, "Username must be 16 characters or less");
    }

    // Check First name
    if ($first_name) {
        if (preg_match('/[^A-Za-z\'\-\s]/', $first_name) || !preg_match('/[A-Za-z]/i', $first_name)) {
            array_push($errors, "First Name is not valid");
        }
        if (strlen($first_name) > 15) {
            array_push($errors, "First name must be 15 characters or less");
        }
    } else {
        array_push($errors, "Must enter a first name");
    }

    //Check Last name
    if ($last_name) {
        if (preg_match('/[^A-Za-z\'\-\s]/', $last_name) || !preg_match('/[A-Za-z]/i', $last_name)) {
            array_push($errors, "Last Name is not valid");
        }
        if (strlen($last_name) > 25) {
            array_push($errors, "Last name must be 25 characters or less");
        }
    } else {
        array_push($errors, "Must enter a last name");
    }

    // Validate e-mail
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        array_push($errors, "Please enter a valid e-mail address");
    }

    if (strlen($email) > 50) {
        array_push($errors, "E-mail address must be 50 characters or less");
    }

    // Check if role is legal
    $role_value = 0;
    if ($role == 'student') {
        $role_value = 1;
    } else if ($role == 'teacher') {
        $role_value = 2;
    } else {
        array_push ($errors, "No role selected");
    }

    // Check if passwords match
    if ($pwd1 != $pwd2) {
        array_push($errors, "Passwords do not match");
    } else {
        // Check if passwords meet criteria
        if (!preg_match('/\W/', $pwd1) || !preg_match('/[0-9]/', $pwd1) ||
        strlen($pwd1) < 10) {
            array_push($errors, "Password is not valid");
        }
    }

// If there are no errors, commit results to DB and create session

if (empty($errors)) {
    // Hash passwords for DB storage   
    $pwd1 = password_hash($login_name . $_POST['password_1'], PASSWORD_DEFAULT);

    /*
        THIS WILL NEED TO BE UPDATED WHEN E-MAIL VALIDATION IS IMPLEMENTED
    */
    // Create query for inserting new data
    $add_user_query = "INSERT INTO `CMP_Users` (User_First_Name, User_Last_Name, "
        . "User_Login, User_Email, User_Password, User_Role, User_Created) VALUES "
        . "(?, ?, ?, ?, ?, ?, NOW())";

    $mysqli_add_user = new mysqli($hostname, $username, $password, $dbname);
    $mysqli_add_user->set_charset("utf8");
    $stmt_add_user = $mysqli_add_user->prepare($add_user_query);
    $stmt_add_user->bind_param("sssssi", $first_name, $last_name, $login_name, $email, $pwd1, $role_value);
    $stmt_add_user->execute();


    // Set session variables
    $_SESSION['username'] = $login_name;
    $_SESSION['role'] = $role_value;
    $_SESSION['email'] = $email;
    $_SESSION['fname'] = $first_name;
    $_SESSION['lname'] = $last_name;
    $connection->close();
    header('Location: http://www.collinmath.com/mathpages/index.php');
    exit();
}

// Close db connection
$connection->close();

}

// Check whether the user is already logged in
// and redirect them to the main user page if they are
if (isset($_SESSION['username'])) {
    header('Location: http://www.collinmath.com/mathpages/index.php');
    exit();
}

?>

UPDATE:

So, I changed a bunch of the code and tinkered with the php.ini file but I'm still having problems. When I look at my cookies, I see the cookie is there. I see the file is created in the sessions folder and that the variables are set in that file, but there is still no session info when I do a var_dump.

My session_save_path and var_dump shows this:

/home/[myname]/sessions/

array(0) { }

and the file that is created in my sessions folder looks like this:

username|s:7:"testerz";role|i:1;email|s:19:"email@email.com";fname|s:4:"First";lname|s:6:"Name";

  • 写回答

2条回答 默认 最新

  • douquanzhan0315 2018-06-02 15:48
    关注

    Problem Fix:

    This is work in progress from the long comment discussion and will be updated as we go

    From what you've told me the logic process of your situation is impossible.

    RE: Your update: Then if the session is definitely being written then there are three possible options:

    1) there is an ini_set() or a directory-local .ini file which is changing the session name so data from one directory is not being recognised in another, as they're looking in different sessions.

    2) You have a spelling or casing issue of your $_SESSION keys.

    3) session_start() has not been initiated.

    Furter debugging and Solution:
    Whenever you var_dump your session data, and it's turning up blank; add these lines:

     error_log(print_r(session_status()."<BR>",true)); 
     error_log(print_r(session_name()."<BR>",true));
     error_log(print_r($_SESSION,true)); //your original  output.
    

    Add this code block to both your data-in page (create.php) and the destination page that is failing to show certain sessions.

    If the above are always exactly the same (and they may be if , as you say, some data does "work".

    Then the answer is that you definitely absolutely have some lines in your code that change the session values. The symptoms look like you've got a screwed up REGEX preg_ function somewhere. Again; use your PHP Error Log to check these things out.

    General Fixes:

    • Quote your array keys; $row[Login] should be `$row['Login']
    • Use a single MySQLi connection, of a single type
    • That type should be the Object Orientated approach (->)
    • Do not use real_escape_string for Object Orientated MySQL connections.
    • Use Multibyte PHP String functions
    • Use UTF8mb4 MySQLi connection character sets, and the same in your tables and columns.
    • Tidy up your code and your logic process, you've made a funtion but the function always runs so it has no benefit being a function - it may as well just be straight code.
    • Don't use globals
    • MySQL does not care about new lines so you don't need to concatenate the SQL strings.
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示