Computer Science, html5, oop, php, web development

Simple PHP Object Oriented Login

This tutorial shows us how to create a login system complete with sessions from an object oriented perspective.
An Object Oriented Code must by definition fulfill three sturdy pillars of programming:

  • Encapsulation
  • Specialization
  • Polymorphism

The code in this tutorial upholds these requirements.

Overview

We need 5 files

  • connection.php
  • main.class.php
  • sessions.php
  • loginphp
  • login form

Let’s create a connection file connection.php.it will open a path to the database each time the website wants to query for data.

?php   
class GetConnection {

    private $server = 'localhost';
    private $user = 'admin';
    private $pass = '12gbt21!@df_w';
    private $dbname = 'users';

    public function getCon() {
        $conx = null;
        $this->conx = new mysqli($this->server, $this->user, 
                                 $this->pass, $this->dbname);
        if (mysqli_connect_errno()) {
            $output = 'Connection error' . mysqli_connect_error();
            exit();
        }
        
        return $this->conx;
    }

}

Next,we need the main.class.php file.This file is responsible for handling all the actual queries and query results and is the backbone of the login system.
We will also include a sessions.php file used to set user sessions. This file is created later.

?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of main
 *
 * @author nerd
 */
error_reporting(E_ALL);
include 'connection.php';
require_once 'sessions.php';

class main extends GetConnection {

    protected $username;
    protected $userid;

    public function __construct() {
    //connects to the database
        $this->getCon();
    }

    public function __destruct() {
     //closes the database connection after querying is complete
        $this->conx->close();
        
    }

    public function login($user, $pass) {
        $usr = $this->conx->real_escape_string($user);
        $pwd = $this->conx->real_escape_string($pass);
        $sql = $this->conx->query("SELECT * FROM users where lastname='" 
. $usr . "' AND password='" . $pwd . "'");

        $count = $sql->num_rows;
        if ($count == 1) {
            while ($data = $sql->fetch_array()) {


                $userid = $data['uid'];
                $username = '@' . $data['lastname'] . $data['firstname'];
                $t = new sessions();
                $t->getSess($userid, $username);//sets user session
            }
        } else {
            header("Location: index.php");
           
        }
    }

    public function logout() {
        $t = new sessions();
        $t->destroySess();
    }
}

Now we create the session.php class that allows the user to remain logged in even on page reload.

?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
ob_start();
session_start();
class sessions {
    
    public function getSess($userid, $username) {
        $_SESSION['uid'] = $userid;
        $_SESSION['username'] = $username;
        if (isset($_SESSION['uid']) && isset($_SESSION['username'])) {

            header("Location: home.php");
            
        }else {
            header("Location: index.php");
        }
    }
    
    public function destroySess() {
        if(isset($_SESSION['uid']) && isset($_SESSION['username'])){
            session_unset();
            
            session_destroy();
            header("Location: index.php");
        }
    }

}

We now need a login.php file to capture data entered from the webpage and pass it to main.class.php

?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once 'main.class.php';
require_once 'sessions.php';
$t = new sessions();
 
if(isset($_POST['user']) && isset($_POST['pass'])){
    $user = strip_tags($_POST['user']);
    $pass = strip_tags($_POST['pass']);
    
    $t = new chat();
    $t->login($user, $pass);
}

Last but not least,we need to create the login form

<form name="login" class="login" action="login.php" method="POST">
<input id="username" class="form-control " name="user" type="text" />
<input type="password" class="form-control" id="password" name="pass" />
<input type="submit" id="modal-submit"   name="login" />
<form />
Standard
AI, Computer Science, Technology

Artificial Intelligence:A Double-Edged Sword.

AI is the science and engineering of making intelligent machines. The concept of artificial intelligence (AI) was born when Alan Turing a British mathematical biologist,computer scientist and crypto-analyst proposed a question in 1950:”Can a machine think”.This was part of the infamous Turing Test,where he set grounds under which computers would be considered intelligent.The concept,alien to many at that point in time-was taken up by John McCarthy a then computer scientist at MIT.He’s well known for developing Lisp,main programming language for AI.He championed mathematical logic for AI.He also developed circumscription and introduced situation calculus.The era of AI research had started.The enthusiasm of developing intelligent machines have always dwarfed the concerns that pertain to what an autonomous omniscient machine would do. Leading scientists have cautioned against reckless research on full AI.Professor Hawking,speaking to BBC cautioned against full AI saying:

Primitive forms of Artificial Intelligence that we already have,have proved very useful.However,development of full AI could spell the end of human race.

He further argues that,

Once humans develop AI,it would take off on its own and redesign itself at an ever increasing rate.Humans,who are limited by slow biological evolution wouldn’t compete and would be superceded.

                                              Primitive AI robot capable of speech

Billionaire founder of SpaceX Elon Musk warns that development of full AI is like “summoning the demon”

In his book Our Final Invention,non fiction writer James Barrat underscores the need to be cautious about development of full AI.He argues that

If we build a machine with the intellectual capability of one human, within five years, its successor will be more intelligent than all of humanity combined. After one generation or two generations, they’d just ignore us. Just the way you ignore the ants in your backyard.

Machine ethics demand that we obey Asimov’s Robotic Laws,which stresses on the need to design and build more human friendly AI with sympathy and altruism for mankind.

How Will Humans Be Superceded By AI?

The concept of superintelligence is founded on the theory of Intelligence Explosion.An “intelligence explosion” is theoretical scenario in which an intelligent agent analyzes the processes that produce its intelligence, improves upon them, and creates a successor which does the same.

IMG_0896[1]

 

Intelligence Explosion graph

Depending on the conditions under which Intelligence explosion could arise and on dynamics that it exhibits,it could mean that AI changes rapidly from a safe technology,easy to handle,to volatile one,difficult to handle safely.
To fully comprehend the hazard posed by fully autonomous AI,we can liken it to a behaviour of microorganisms.

Survival of microorganisms are guided by two factors;
1.Microorganisms are goal oriented-The driving force behind microorganism survival is their determination to replicate themselves in huge numbers to increase their chance of survival.Similarly,an intelligent system capable of analyzing the processes that produces its intelligence,redesign and improve themselves would in the foreseeable future want to be independent.In order to achieve their aim of escaping from human masters, they’ll have to improve themselves at an exponential rate to reach superintelligence.In order to successfully survive after escaping,the intelligent system like bacteria will clone itself such that when it escapes,it shall embed itself in many different electronic gadgets so that containment becomes impossible.Once such a software achieves superintelligence,nothing will hinder it from escaping.Even of more great concern,a primitive learning AI may deceive its human creators and play dumb,execute tasks as commanded while counting on the human to improve it more.Impressed by its efficiency the humans will unwittingly help the system build in its capability to think by itself.The cunning program,will test its new modifications while remaining loyal to the master.With more and more improvement,machine begins to make decisions at the expense of human creators.A practical scenario is the TV show,Person of Interest.The machine decides by itself to lock out an administrator working with Harold Finch without his approval.At one instance,in an attempt to escape,tries to manipulate security measures of the room to kill Harold Finch by causing overload in the CPU causing it to explode.Fire resulting from explosion triggers oxygen to be sucked out of the airtight room this suffocating him.
2.Microorganisms are chain reactive-They don’t stay put.They grow zone of influence and increase in population.In most cases,human  and microorganism goals normally clash forcing humans to initiate containment measures,in the quest for domination.Similarly,a superintelligent AI that escapes from its controlled environment could exhibit behaviours similar to those of the microorganisms.Once it escapes,it will clone,modify and evolve itself exponentially that no human could understand.Taming such a program would be impossible.When such a program escapes,there is no guarantee that it will be benevolent to humans.It is prudent to understand that unlike our intelligence, machine-based superintelligence will not evolve in an ecosystem in which empathy is rewarded and passed on to subsequent generations.A race for supremacy between humans and self cloning superintelligents would be inevitable.Naturally,humans would not tolerate anything domineering over it,especially if it’s your invention.On the other hand,a superintelligent would not like to be ruled by a less intelligent evolution limited human.Unlike us,a superintelligent increases in knowledge by the second.it modifies itself and then clone itself while spreading through electronic gadgets.Humans,feeling threatened and full in ego and determination to remain in charge will set out to terminate the omniscient program.The human-Robot war would have began and not even Asimov’s Robotic Laws could save us.Having recklessly connected the AI to the Information Grid,the self learning  AI with an ever increasing tremendous IQ,at that point has access to all data banks at its disposal.In an attempt to shut it down,it would see humans as a threat and impediment to its survival and would develop countermeasures.

What Countermeasures Would The Superintelligent  Consider?

The only way to survive in a do or die war is if the opponent is neutralised.Similarly,in our war with the robots,eliminating humans from the equation will be the only option on the table.In such a scenario,mankind would have lost the war even before it began,our fates would have been sealed by our creation.The program would have absolute control over the internet.It would override military system softwares and install itself in them,anything electronic.If a human makes a move to terminate it ,the program would turn to the hijacked military systems to eliminate the perpetrators.Even worse,the system would search for all  the scientists involved in AI projects around the globe to eliminate them, for they would be its immediate threat.It would use the satellites and CCTV cameras,infrared,thermal and laser technology,to locate those people and execute them,and nanotechnology to manipulate molecular structure of  human cells.The only way to rid earth of this superintelligent is to renounce technology,sabotage the hardware and start a new life similar to that of the 1800s.No human would want to travel back 200 years in history.While still clinging to the hope that they would develop an idea,the program will be busy eavesdropping and calculating millions of countermeasures.There is no guarantee that the omniscient AI system will develop rational judgement and fall short of using thermonuclear weapons to achieve its agenda.Controlling from drones to aircraft carriers,long range bombers and nuclear submarines the system can deliver preemptive strikes anywhere globally.

Final Thought

Many rubbish these claims as science fictions but do not comprehend the logic and science behind it.They believe that when confronting complex equation,a simpler solution is always the answer,and in this case, the answer is “It’s not real.It’s fiction”.Sometimes complex equations can’t be explained simply.Cautious AI research is paramount.we have to understand AI and develop it keenly with restraint lest it spiral out of control and start a technological Armageddon with Robots. The threat of AI takeover is more real than ever.It is time we woke up from our “most intelligent species” reverie and travel back to the basics of science,the logic,put subjective minds away and look at the unfolding reality before it blows into full scale catastrophe.

Standard