Welcome Guest, Not a member yet? Register   Sign In
Requesting $_POST is empty while is not empty in var_dump()
#1

** Very new to CodeIgniter **

I am not sure what's wrong. I have two forms login.php and register.php and both of them (upon inspecting in browser and doing a var_dump()) are correctly storing the post input values. However, when I try to access the post input in my controller using $this->request->getPost() the input fails the 'required' rule upon validation as if post is empty.


PHP Code:
VAR_DUMP($LOGIN):
array(
2) { ["username"]=> string(6"AgBRAT" ["password"]=> string(10"abcABC123!" 

ROUTES:
// Login and Registration
$routes->match(['get''post'], 'users/register''Users::register');
$routes->match(['get''post'], 'users/login''Users::login', ["filter" => "noauth"]);

USERMODEL.PHP:
class 
UserModel extends Model
{
    protected $DBGroup          'default';
    protected $table            'users';
    protected $primaryKey      'username';
    protected $useAutoIncrement false;
    protected $insertID        0;
    protected $returnType      'object';
    protected $useSoftDelete    false;
    protected $allowedFields    = [
        'username',
        'password',
        'id',
        'role',
        'profile_image',
        'profile_views',
        'last_login',
        'about_me',
        'age',
        'gender',
        'occupation',
        'hometown',
        'country',
        'fav_shape',
        'fav_color',
        'created',
        'modified',
    ];

    // Dates
    protected $useTimestamps    true;
    protected $dateFormat      'datetime';
    protected $createdField    'created';
    protected $modifiedField    'modified';

    // Callbacks
    protected $beforeInsert = ['beforeInsert'];

    public function __construct() 
    {
        parent::__construct(); 
    }

    protected function beforeInsert(array $data)
    {
        $data $this->passwordHash($data);

        return $data;
    }

    protected function passwordHash(array $data)
    {
        if (isset($data['data']['password'])) {

            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        }

        return $data;
    }

      public function lastLogin($username)
    {
        $this->builder()
            ->where('username'$username)
            ->update('last_login'date('Y-m-d H:i:s'));
    }

    protected function addUser($newUser)
    {
        $builder $this->builder()->insert($newUser);

        if ($builder->affected_rows() == 1) {

            return TRUE;

        } else {

            return FALSE;
        }
    }

    public function getUser($username)
    {
        $builder $this->builder()
            ->where(['username' => $username])
            ->limit(1);

        if ($builder->countAllResults() === 1) {

            return $builder->get()->getRow();

        } else {

            return FALSE;
        }
    }
}

USERS.PHP:
class 
Users extends BaseController
{
    protected $userModel;

    public function __construct () 
    {
        $userModel = new UserModel();
    }

    public function login()
    {
        $validation = \Config\Services::validation();

        // Set session variable
        $session session();

        if ($this->request->getMethod() === 'post' && ! empty($_POST)) {

            $login = [
                'username'  => $this->request->getPost('username'),
                'password'  => $this->request->getPost('password'),
            ];

            $validation->getRuleGroup('login');
            $validation->setRuleGroup('login');
            $validation->run($login'login'); 

            $recaptchaResponse trim($this->request->getPost('g-recaptcha-response'));

            $userIp $this->request->getIPAddress();

            $secret env('recaptcha2_secretkey');

            $credential = [
                'secret'    => $secret,
                'response'  => $recaptchaResponse,
                'remoteip'  => $userIp,
            ];

            $verify curl_init();

            curl_setopt($verifyCURLOPT_URL'https://www.google.com/recaptcha/api/siteverify');
            curl_setopt($verifyCURLOPT_POSTTRUE);
            curl_setopt($verifyCURLOPT_POSTFIELDShttp_build_query($credential));
            curl_setopt($verifyCURLOPT_SSL_VERIFYPEERFALSE);
            curl_setopt($verifyCURLOPT_RETURNTRANSFERTRUE);

            $response curl_exec($verify);

            $status json_decode($responseTRUE);

            curl_close($verify);

            if (empty($validation->getErrors()) && $status['success']) {

                $username $login['username'];

                $user $this->userModel->getUser($username);

                // Storing session values
                $this->setUserSession($user);

                // Storing success message
                $session->setFlashdata('success''You have successfully logged in!');

                // Update last login datetime
                $this->userModel->lastLogin($login['username']);

                // Save last login
                $lastLogin = [
                    'last_login'  => $this->request->getVar('last_login'),
                ];
                $userModel->update($_SESSION['username'], $lastLogin);

                // Redirecting to dashboard after login
                if ($user['role'] == 1) {

                    return redirect()->to('admin/dashboard');

                } elseif ($user['role'] == 0) {

                    return redirect()->to('members/dashboard');
                }
            } else {

                $data = [
                    'title'    => 'Login',
                    'errors'    => $validation->getErrors(),
                    'login'    => $login,
                ];

                echo view('templates/index_header'$data);
                echo view('users/login');
                echo view('templates/footer'$data);
            }  
        
} else {
            $data = [
                'title' => 'Login',
                'login' => 'NULL',
            ];

                echo view('templates/index_header'$data);
                echo view('users/login');
                echo view('templates/footer'$data);  
        
}
    }

    /**
    * Sets session with user id, username, isLoggedIn, and role for use in member/admin site
    * @param model user data
    * @return boole if session was set successfully
    */
    private function setUserSession($user)
    {
        $data = [
            'id' => $user->id,
            'username' => $user->username,
            'profile_image' => $user->profile_image,
            'isLoggedIn' => true,
            'role' => $user->role,
        ];

        if (session()->set($data)) {

            return true;

        } else {

            return false;
        }
    }

    public function register() 
    {
        $validation = \Config\Services::validation();

        if ($this->request->getMethod() == 'post' && ! empty($_POST)) {

            $newUser = [];

            $newUser = [
                'username' => $this->request->getVar('username'),
                'password' => $this->request->getVar('password'),
                'role' => $this->request->getVar('role'),
                'modified' => $this->request->getVar('modified'),
                'about_me' => $this->request->getVar('about_me'),
                'age' => $this->request->getVar('age'),
                'gender' => $this->request->getVar('gender'),
                'occupation' => $this->request->getVar('occupation'),
                'country' => $this->request->getVar('country'),
                'fav_shape' => $this->request->getVar('fav_shape'),
                'fav_color' => $this->request->getVar('fav_color'),
            ];

            $validation->getRuleGroup('registration');
            $validation->setRuleGroup('registration');
            $validation->run([$newUser], 'registration'); 

            if (empty($validation->getErrors())) {

                if ($this->userModel->addUser($newUser)) {

                    $this->session->setFlashdata('success''Successful Registration');

                    $data['title'] = 'Login';

                    echo view('templates/index_header'$data);
                    echo view('users/login');
                    echo view('templates/footer'$data);

                } else {

                    $this->session->setFlashdata('error''Something went wrong with your registration! Please try again.');
                }

            } else {

                $data = [];

                $data = [
                    'title'    => 'Register',
                    'script'    => 'js/click_link',
                    'errors'    => $validation->getErrors(),
                ];

                echo view('templates/index_header'$data);
                echo view('users/register'$data);
                echo view('templates/footer'$data);
            }
        } else {
            $data = [
                'title'        => 'Register',
                'script'        => 'js/click_link',
            ];

            echo view('templates/index_header'$data);
            echo view('users/register'$data);
            echo view('templates/footer'$data);
        }
    }

USERS/LOGIN.PHP:
<
div class='form-container'>

    <?= form_open('users/login',['autocomplete' => 'off']); ?>

        <div class='form-header'>
            <h2>Login</h2>
        </div>

        <div class='form-body'>

            <div class='form-row'>
                <div class='input-container'>
                    <i class='fas fa-user'></i>

                    <?php $attributes = [
                        'type'      => 'text',
                        'name'      => 'username',
                        'class'    => 'input-field',
                        'id'        => 'username',
                        'placeholder'  => 'Username',
                        'required'      => TRUE,
                    ]; ?>
                    <?= form_input($attributes); ?>

                </div>
            </div>

            <div class='form-row'>
                <div class='input-container'>
                    <i class='fas fa-lock'></i>

                    <?php $attributes = [
                        'type'          => 'password',
                        'name'          => 'password',
                        'class'        => 'input-field',
                        'placeholder'  => 'Password',
                        'required'      => TRUE,
                    ]; ?>
                    <?= form_input($attributes); ?>

                </div`>
            </div>
        </div>

        <div class='captcha-container'>
            <div class='g-recaptcha' data-sitekey='<?= env('recaptcha2_sitekey'); ?>'></div>
        </div>

        <div class='form-footer'>

            <?php $submit = [
                    'name'      => 'loginSubmit',
                    'value'    => 'Login',
                    'class'    => 'submit-btn',
            ];?>
            <?= form_submit($submit); ?>

        </div>

        <h4 style='text-align: center'>Not a member yet? Register 
            <a href= <?= site_url('users/register'); ?> title = 'Register'> HERE</a>
        </h4>

    <?= form_close(); ?>

    <?= var_dump($login); ?>
</div>

USER_RULES.PHP:
class User_rules 
{
    /**
    * Checks if input username exists in database and then checks whether the input password matches the hash for that username
    * @param string $str is the input password
    * @param string $fields are the associated form fields that are being used
    * @param array $data is an array containing the values for the fields indexed by field names
    * @return boolean true or false depending on if the user exists and the password matches the hashed password stored in the database
    */
    public function validateUser(string $str, string $fields, array $data)
    {
        $userModel = new UserModel();

        $user = $userModel->getUser($data['username']);

        if(!$user) {

            return FALSE;
        }

        return password_verify($data['password'], $user->password);
    }



Output of ```var_dump($login)``` is:** Very new to CodeIgniter **

I am not sure what's wrong. I have two form
Reply
#2

In beforeInsert you have "$data (minus) $this->passwordHash($data)" should be an equal sign I guess.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB