简体   繁体   中英

PHP Auto Login after Registration

I'm having some issues with a request from my boss.

I'm using the http://www.html-form-guide.com/ Registration forms he has created for use (I've attached the link just in case anyone want to use or look at it)

So I'm pretty new to PHP, but I've been gaining a crazy amount of knowledge.

Here is my problem - I need to make this form Register the user than Login Automatically . (This form has a Email confirmation system)

So I've managed to bypass the Email Confirmation and get the user to register, but I can't seem to figure out how to get auto login.

Here is what I've traced in the code:

    function RegisterUser()
{
    if(!isset($_POST['submitted']))
    {
       return false;
    }

    $formvars = array();

    if(!$this->ValidateRegistrationSubmission())
    {
        return false;
    }

    $this->CollectRegistrationSubmission($formvars);

    if(!$this->SaveToDatabase($formvars))
    {
        return false;
    }

    /*if(!$this->SendUserConfirmationEmail($formvars))
    {
        return false;
    }*/

    $this->SendAdminIntimationEmail($formvars);

    $this->AutoLogin($formvars);// My call

    return true;
}

This will pull in the name, email and password - put them in an array then send it off for validation and sanitation. I've placed a call function here.

After which I'll need to manually login with:

function Login()
{
    if(empty($_POST['email']))
    {
        $this->HandleError("Email is empty!");
        return false;
    }

    if(empty($_POST['password']))
    {
        $this->HandleError("Password is empty!");
        return false;
    }

    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if(!isset($_SESSION)){ session_start(); }
    if(!$this->CheckLoginInDB($email,$password))
    {
        return false;
    }

    $_SESSION[$this->GetLoginSessionVar()] = $email;

    return true;
}

So I took the last portion of the login function and made:

    function AutoLogin(&$formvars)
{
    $email = trim($formvars['email']);
    $password = trim($formvars['password']);

    if(!isset($_SESSION)){ session_start(); }       
    if(!$this->CheckLoginInDB($email,$password))
    {
        return false;
    }

    $_SESSION[$this->GetLoginSessionVar()] = $email;

    return true;
}

I did an echo $email; echo $password; exit; test and I can see that the email and password are appearing. But the "Session" (I think) is not starting or the Check Login is not getting the data.

    function CheckLogin()
{
     if(!isset($_SESSION)){ session_start(); }

     $sessionvar = $this->GetLoginSessionVar();

     if(empty($_SESSION[$sessionvar]))
     {
        return false;
     }
     return true;
}

Now I see the is a CheckLoginInDB which is:

    function CheckLoginInDB($email,$password)
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }          
    $email = $this->SanitizeForSQL($email);
    $pwdmd5 = md5($password);
    $qry = "Select name, email, pagecode, welcome from $this->tablename where email='$email' and password='$pwdmd5' and confirmcode='y'";

    $result = mysql_query($qry,$this->connection);

    if(!$result || mysql_num_rows($result) <= 0)
    {
        $this->HandleError("Error logging in. The email or password does not match");
        return false;
    }

    $row = mysql_fetch_assoc($result);

    $_SESSION['name_of_user']  = $row['name'];
    $_SESSION['email_of_user'] = $row['email'];
    $_SESSION['pagecode_of_user'] = $row['pagecode'];
    $_SESSION['welcome_user'] = $row['welcome'];

    return true;
}

What I can gather from this, its just a standard checking the database to see if this user exists and returning the results.

I've searching through stackoverflow and can't seem to see an answer to my problem.

I looked into Cookies, but I don't think that is something I really need here.

My questions are:

How can I make this bad boy start the session on registration?

Is my thinking on calling the AutoLogin(&$formvars) the right idea?

Have I gone wrong with this AutoLogin function syntax?

Just in case here is the GetLoginSessionVar():

    function GetLoginSessionVar()
{
    $retvar = md5($this->rand_key);
    $retvar = 'usr_'.substr($retvar,0,10);
    return $retvar;
}

It's a pity I can't attached the file I'm working on, but if you need any further code snippets let me know and I'll be sure to Edit this straight away!

But the "Session" (I think) is not starting or the Check Login is not getting the data. Is my thinking on calling the AutoLogin(&$formvars) the right idea? Have I gone wrong with this AutoLogin function syntax?

It's not something wrong with the syntax, otherwise the code wouldn't even be compiled. Nevertheless I believe it's not the right idea.

You need to understand what's the problem before trying to fix it. Debug the code. Use xdebug. If it's installed and active, you can use IDEs (eg: Visual Studio Code) to easily debug the code. Add breakpoints where you suspect there's something wrong.

If you don't want to use xdebug, you can add temporarily echoes or var_dumps to check if some areas of the code are processed and check some relevant values.

Also enable all errors reports and use a logger. If the session is started after any output, there should be some warning. Handle the errors and throw exceptions.

You don't need to use the & in AutoLogin(&$formvars) if you're not changing the argument $formvars (you're just reading it).

You don't need to set session variables with all the user data. Create some structure (a class, an array, ...) with the user data outside those function and change those. AutoLogin should update that structure, something like this:

<?php

if (!$_SESSION) {
    session_start();
}

$currentUser = array();

function getUserFromID($userID)
{
    //TODO implement function
    return $user;
}

function AutoLogin()
{
    global $currentUser;
    if(!empty($_SESSION['userID'])) {
        return false;
    }

    $user = getUserFromID($_SESSION['userID']);
    if (empty($user)) {
        return false;
    }
    $currentUser = $user;
    return true;
}

Maybe the session is not initialised before CheckLoginInDB is invoked (make var_dump($_SESSION); to check it). Use the $_SESSION only to save the user ID (or email) and read it to retrieve the user data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM