Page 1 of 1

refactor class for HTTP request

Posted: Sun Feb 14, 2021 11:08 am
by iago
Hello,

I wrote an HTTP class in order to handle my http requests from the front-end. My question to the php pros here is, how can I refactor it concerning security and performance.
The DB class uses PDO + prepared statements and should be o.k. So I just want to focus on the HTTP class.

E.g. I submit $_GET and $_POST as parameters for the constructor. I think I don't have to do this, because both are superglobals, but I don't "feel" well accessing them just like that.

Here is the code: Thanks!

Code: Select all

class HTTP {

    private $_httpAction;
    private $_postParams = [];
    private $_trimmedSectionId;
    private $_user;
    private $_timestamp;

    public function __construct($action,&$post) {
        $this->_db = DB::getInstance();
        $this->_httpAction = $action;
        $this->_postParams = $post;
        $this->_sessionName = Config::get('session/session_name');
        $this->_timestamp = date('Y-m-d H:i:s');


         if(Session::exists($this->_sessionName)) {

            $this->_user = Session::get($this->_sessionName);
           
        }  else {

            // error, session does not exist
        }

        if(isset($this->_postParams['section_id'])) {
            $this->_trimmedSectionId = ltrim($this->_postParams['section_id'],'section');

        }
    }

    public function http_exec() {

        switch($this->_httpAction) {

           case 'newCP' : $this->newCP();
           break;
           case 'updateCP' : $this->updateCP();
           break;
           case 'delCP' : $this->delCP();
           break;


        }
    }

    private function newCP() {

         $this->_db->insert('cpicks',array(
            'section_id' => $this->_trimmedSectionId,
            'user_id' => $this->_user,
            'label' => $this->_postParams['newCpHeadline'],
            'text' => $this->_postParams['newCpArea'],
            'new_datetime' => $this->_timestamp
        ));
    }

    private function updateCP() {

         $this->_db->cpUpdate('cpicks',$this->_postParams['cp_id'],array(
                'label' => $this->_postParams['cp_headline'],
                'text' => $this->_postParams['sectionText'],
                'update_time' => $this->_timestamp,
           ));

    }

    private function delCP() {

         $this->_db->delete('cpicks',array('cp_id','=', $this->_postParams['cp_id']
    ));
    }

}
http.php

Code: Select all


require_once 'core/init.php';

$user = new User();

 if($user->isLoggedIn()) {

   

        $request = new HTTP(Input::get('action'),$_POST);
        $request->showPostandGet(); 

        $request->http_exec();

    
 }
Input helper class:

Code: Select all

   public static function get($item) {
        if(isset($_POST[$item])) {

            return $_POST[$item];
        }

        if(isset($_GET[$item])) {

            return $_GET[$item];
        }

        return '';

    }