Activating account with php oop language

The $SERVER variable is never defined.
See post #13.

1 Like

Again, this is incorrect. I have told you before, $_SERVER DOES NOT contain email nor token in the array. You don’t seem to understand the difference between the two. This is where I disagree with using tutorials. Tutorials fail to describe what each function is supposed to be used for. Instead, all they “try” to show you is what “they only want” to show you.

The correct way is to include both $_SERVER and $_POST variables. $_SERVER for form submission checking and $_POST to grab what the user typed in.


Let me elaborate and educate you.


The $_SERVER variable describes what is inside the server output. If we do a print_r on $_SERVER, we will find out exactly what the $_SERVER variable contains.

print_r($_SERVER);

The output is

Array
(
    [HTTP_HOST] => localhost.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/ *;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_CONNECTION] => keep-alive
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [PATH] => /usr/bin:/bin:/usr/sbin:/sbin
    [SERVER_SIGNATURE] => 
    [SERVER_SOFTWARE] => Apache/2.4.29 (Unix) LibreSSL/2.2.7 PHP/7.2.2
    [SERVER_NAME] => localhost.com
    [SERVER_ADDR] => 127.0.0.1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 127.0.0.1
    [DOCUMENT_ROOT] => /var/www/html/default
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] => 
    [CONTEXT_DOCUMENT_ROOT] => /var/www/html/default
    [SERVER_ADMIN] => webmaster@localhost.com
    [SCRIPT_FILENAME] => /var/www/html/default/demo/index.php
    [REMOTE_PORT] => 53589
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] => 
    [REQUEST_URI] => /demo/
    [SCRIPT_NAME] => /demo/index.php
    [PHP_SELF] => /demo/index.php
    [REQUEST_TIME_FLOAT] => 1522491556.95
    [REQUEST_TIME] => 1522491556
)

And if we look closely, the reason why we are using $_SERVER is to do form submission checking. This means that we are trying to check whether the form was submitted either through GET or POST. We want POST since this deals with user submission. So using $_SERVER, the index that allows us to check for this is REQUEST_METHOD. Therefore, we should use $_SERVER['REQUEST_METHOD'] for the form submission checking.

$_POST describes everything that is submitted through a form using the attribute method="POST". The POST array will contain anything from form fields to radio buttons to check boxes and other form related things like selectable drop down menus.

Next, the only reason why you should be using if(isset($_POST['...'])) and the like is through form validation. There is a difference between form submission checking and form validation. Form submission checking is the act in which one tries to check whether a certain method is set. There are only 2 methods and that is GET and POST. GET deals with getting data from the URL. Typically, things like search engines deal with this. You shouldn’t use GET for user submission though. This is a terribly bad idea. The correct way is to use POST since it deals with user submission. Typically for log in pages or any sensitive data that shouldn’t be passed into the URL where people can see.

Now, form validation is pretty much when you want to validate and verify that what the user typed in is what you want it to be. For instance, if you have a date (1-31), you don’t want them to pass in say “one” do you? So for form validation, you want them to only type in numbers. In this case, you can do it in many ways. You could type cast and force the input to be an int or you could throw the input in an if statement and use is_int to check whether it is a number or not. This is form validation. This is the only time where using if(isset($_POST['...'])) should be allowed. The reason being is because if you don’t use it in form validation, then you will get an Undefined Index error if you have people playing with the HTML page.

1 Like

So I guess from my understanding, I just have to include this line

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST');

but I have tried to use both these codes but can’t call my user class

$user->data()->username..

I do have the function data() in my user.php file…


public function data() {
		return $this->_data;
	}

Correct.

Show the code for this method.

I am confused because I think that is all I have… I have been following a tutorial from codecourse but they didn’t write anything else for that code

This is the code from my user.php file

<?php
class User{
	private $_db,
	        $_data,
	        $_sessionName,
	        $_cookieName,
            $_isLoggedIn;

	public function __construct($user = null) {
		$this->_db = DB::getInstance();

		$this->_sessionName = Config::get('session/session_name');
        $this->_cookieName = Config::get('remember/cookie_name');

		if(!$user) {
           if(Session::exists($this->_sessionName)) {
              $user = Session::get($this->_sessionName);

              if($this->find($user)) {
              	$this->_isLoggedIn = true;
              } else {

              }
           }
        } else {
        	$this->find($user);
        }
	}

	public function update($fields = array(), $id = null) {

	   if (!$id && $this->isLoggedIn()) {
          $id = $this->data()->id;
	   }

       if(!$this->_db->update('users', $id, $fields)) {
          throw new Exception('There was a problem updating.');
       }
	}

	public function create($fields = array()) {
		if(!$this->_db->insert('users', $fields)) {
           throw new Exception('There was a problem creating an account.');
		}
	}

	public function find($user = null) {
       if($user) {
          $field = (is_numeric($user)) ? 'id' : 'username';
          $data = $this->_db->get('users', array($field, '=', $user));

          if($data->count()) {
          	$this->_data = $data->first();
          	return true;
          }
       }

       return false;
	}

	public function login($username = null, $password = null, $remember = false) {
        

        if(!$username && !$password && $this->exists()) {
           Session::put($this->_sessionName, $this->data()->id);
        } else {
           $user = $this->find($username);	
        
        
        if($user) {
        	if($this->data()->password === Hash::make($password, $this->data()->salt)) {


               echo 'ok';
               Session::put($this->_sessionName, $this->data()->id);

               if($remember) {
                  $hash = Hash::unique();
                  $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                  if(!$hashCheck->count()) {
                     $this->_db->insert('users_session', array(
                        'user_id' => $this->data()->id,
                        'hash' => $hash
                     ));
                  } else {
                  	   $hash = $hashCheck->first()->hash;
                  }

                  Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
               }
               return true;
        	}
        }
    }
       
        return false;
	}








	public function hasPermission($key) {
       $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

       if($group->count()) {
          $permissions = json_decode($group->first()->permissions, true);

          if($permissions[$key] == true) {
             return true;
          }
       }
       return false;
	}

	public function exists() {
		return (!empty($this->_data)) ? true : false;
	
	       
	}

	public function logout() {

		$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

		Session::delete($this->_sessionName);
		Cookie::delete($this->_cookieName);
	}

	public function data() {
		return $this->_data;
	}

	public function isLoggedIn() {
		return $this->_isLoggedIn;
	}

  public function email($to, $subject, $body) {
     mail($to, $subject, $body, 'From: pianoforte0011@gmail.com');
  }

}

Let’s take it back a step. What’s in this file?

That is my connection to my database…

session_start();   // allow people to log in

$GLOBALS['config'] = array (
   'mysql' => array(
       'host' => '127.0.0.1',  
       'username' => 'root',
       'password' => '',
       'db' => 'lr'                     
   	),
   'remember' => array(
      'cookie_name' => 'hash',
      'cookie_expiry' => 604800    
   	),
   'session' => array(
      'session_name' => 'user',
      'token_name' => 'token'
   	)
);

spl_autoload_register(function($class) {              // spl=standard php library 
   require_once 'classes/'.$class.'.php';
   
});

require_once 'functions/sanitize.php';

if(Cookie::exists(Config::get('remember/cookie_name')) && !Session::exists(Config::get('session/session_name'))) {
   $hash = Cookie::get(Config::get('remember/cookie_name'));
   $hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));

   if($hashCheck->count()) {
      $user = new User($hashCheck->first()->user_id);
      $user->login();
   }


}














/* Use 127.0.0.1 instead of localhost because of dns lookup, which will take very long for the page to laoad*/

Yeah, I don’t see where you have the username method anywhere. What are you trying to do exactly? Are you trying to sign up with an account?

It might be easier if i paste the youtube videos that I have been following here because I am basing this on the php oop singleton’s method.

Ok, but what are you really trying to do? I know that you are trying to base it off the videos, but this isn’t in the videos. So what are you trying to do? Because it looks like you are trying to use a form to submit the email and token which you shouldn’t be. If you are trying to activate the account, don’t use if($_SERVER['REQUEST_METHOD'] == 'POST') or anything that deals with $_POST.

To activate a user account, they must have the email and token which I assume you are trying to attempt to use. What you need to do in this case is to check whether the email and token are in the URL. Once you can confirm that those parameters are in the URL, you then will need to grab the data from the database. Make sure that the email exists and that the token matches the one from the database. If it doesn’t, redirect them back to a log in page. If the email does exist with the correct token, then change or set the user account to have an activated status. After you do that, then redirect them back to the log in page.

I ma trying to follow this actual video but the coding is out of date I think…

Yes, it is old. He references SMTP. You should be using that instead of mail().

Thanks… In the meantime, I will use mail() but will switch to phpmailer… can you help me through that tutorial based on php oop?

I would have to pass on this and allow someone else to help you. I don’t condone the use of old codes because I don’t want to participate in the legacy. If you want help with PHPMailer, I will then help you.

But I thought that you could help me here with php oop? I just need some guidance to do this email activation but using php oop language

Look at my post on #32. I pretty much told you the answer to doing this.

I just thought that maybe you or someone else could help me to understand the syntax and why I can’t get my $user->data()->username to work. He got it to work in the video…

Let me see the entire file where this is being used. I am a bit confused because you are pasting random stuff which makes it hard to follow. I am talking about where $user->data()->username is being used. Is this within the User.php file? Is this within the Profile.php file? Is this in the Index.php file? Where is this? There’s bits of everything randomly posted before I asked where $this->_data was coming from.

sorry for the confusion… I will check carefully … I am confused myself…

I am referring to these.


Please only paste the relevant parts that you are having issues with. We can then take it step by step to seeing where the problem lies.