PHP Login

From KOP KB
Revision as of 18:15, 14 January 2015 by ReMaster (talk | contribs) (PHP MyAdmin Create database)
Jump to: navigation, search

As a note if you have full access to the hosting via FTP but still want to use the website builder this can work with that as it checks via javascript

PHP MyAdmin Create database

Setting up the First Page

I name the file myself to mlogin.php but its mostly html thats the function. I made it php so if I needed to do anything with it I can

<?
session_start();
$rand ="";
//gen the random number
for ($x=0; $x<32; $x++) {
  $rand = $rand . mt_rand(0,9);
}
//kill the comparison cookie
setcookie("sesscompa", "$rand", time()-3600);
setcookie("sesscompb","$rand", time()-3600);

//starting and overwriting the first cookie
setcookie("sesscooka", "$rand", time()+3600);
setcookie("sesscookb","$rand", time()+3600);
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="clogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Checking the Login

Top of Page

<?php
$host="mysqlv105"; // Host name
$username="sgphplogin"; // Mysql username
$password="Sgphplogin1"; // Mysql password
$db_name="sgphplogin"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];


// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$checkpassword= md5($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$checkpassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
$rand ="";
for ($x=0; $x<32; $x++) {
  $rand = $rand . mt_rand(0,9);
} 

//setting the comparison cookie
setcookie("sesscompa","$rand", time()+3600);
setcookie("sesscompb","$rand", time()+3600);

header("location:loggedin.php");
}
else {
echo "Wrong Username or Password";
header("location:mlogin.php");
}
?>

Logged in Page

Top of Page

<html>
<header>
<script>
function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
    }
    return aString;
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
var sesscooka =getCookie("sesscooka");
var sesscookb =getCookie("sesscookb");
var sesscompa =getCookie("sesscompa"); 
var sesscompb =getCookie("sesscompb");

var n = sesscooka.localeCompare(sesscookb);
var m = sesscompa.localeCompare(sesscompb);

if(sesscompa == ""){
window.location.assign("http://domain.com/loginpage.php")

}else{
if (n == 0){
    if(m == 0)
	{
         /*
         You do not necessarily have to put anything here if you don't want to
         You can put in a log-in successfully but the main point is that its properly checked that they are logged in
         */

	}
	else{
	window.location.assign("http://domain.com/loginpage.php")
	}
}else{
window.location.assign("http://domain.com/loginpage.php")
}
}
</script>
</header>
<body>
Login Successful<br />
</body>
</html>

Another Method Sqlite

Top of Page
Due to other servers not having the same means to do what you need with sqlite this is another method you can use to create the logins.

The DB Construct

This is the construct that recreates the database as an object. Each time you need the database you will call this into a new DB.

<?

//create start
 class MyDB extends SQLite3
   {
      function __construct()
      {
         $this->open('test.db');
      }
   }

Dropping the Database

This is mostly a testing script to show the ability of being able to do a password and login script without a traditional database. This drops the table so it can be recreated without error.

   $db = new MyDB();
   if(!$db){
      echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully<br />";
   }

   $sql =<<<EOF
      DROP TABLE COMPANY;
EOF;

   $ret = $db->exec($sql);
   if(!$ret){
      echo $db->lastErrorMsg();
   } else {
      echo "Kicked Tables successfully<br />";
   }
   $db->close();

Table Creation

Nothing to complicated just using basic SQL to create the table.

   $db = new MyDB();
   if(!$db){
      echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully<br />";
   }

   $sql =<<<EOF
      CREATE TABLE COMPANY
      (ID INT PRIMARY KEY     NOT NULL,
      user           TEXT    NOT NULL,
      pass            TEXT     NOT NULL);
EOF;

   $ret = $db->exec($sql);
   if(!$ret){
      echo $db->lastErrorMsg();
	  echo "<br />";
   } else {
      echo "Table created successfully<br />";
   }
   $db->close();
   //create finish

Inserting the Data

Top of Page
Here were showing inserting just clear text but when you apply it you should hash it with md5 or stronger in your application.

   //insert start
   
   
   $db = new MyDB();
   if(!$db){
      echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully<br />";
   }

   $sql =<<<EOF
      INSERT INTO COMPANY (ID,user,pass)
      VALUES (1, 'Paul', '32' );

      INSERT INTO COMPANY (ID,user,pass)
      VALUES (2, 'Allen', '25' );

      INSERT INTO COMPANY (ID,user,pass)
      VALUES (3, 'Teddy', '23' );

      INSERT INTO COMPANY (ID,user,pass)
      VALUES (4, 'Mark', '25' );
EOF;

   $ret = $db->exec($sql);
   if(!$ret){
      echo $db->lastErrorMsg();
   } else {
      echo "Records created successfully<br />";
   }
   $db->close();
   //insert finish

Showing The Data

As I said this is a testing script to verify you can go this way on a server without using traditional database server methods. Also to prove the information is going in correctly.

   //select start
    $db = new MyDB();
   if(!$db){
      echo $db->lastErrorMsg();
   } else {
      echo "Opened database successfully<br /><br />";
   }
// You will be changing your query for a specific username and password. You would be reading the ones that were inputted through a form.
   $sql =<<<EOF
      SELECT * from COMPANY where user like '%p%';
EOF;
$rc = 0;
   $ret = $db->query($sql);
   while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
      echo "ID = ". $row['ID'] . "<br />";
      echo "user = ". $row['user'] ."<br />";
      echo "pass = ". $row['pass'] ."<br />";
      echo  "<br />";
        // Counter for amount of records it makes it important to ensure the correct person logged in
	  $rc++;
   }
   echo "Operation done successfully<br /><br />";
   //select finish
$db->close();

Displaying the counter

Top of Page
There reason you show the counter so you can make sure the method you have chosen is counting it correctly so when you finish the login script

echo $rc;
echo "<br /><br />";

?>

Yet another method for SQLite

Depending on the software on the server this is yet another method you can use. Even if the server says it has PDO SQLite does not necessarily mean it has the right version for this application.

<?
$dbname = "test.db";
$tablename = "members";


//checking if the table exists or not
if ($db = new PDO("sqlite:$dbname")) {
	$query = @$db->query("SELECT * FROM $tablename");
	if ($query === false) {
		$db->query("CREATE TABLE $tablename (
		           id INT NOT NULL ,
		           username text NOT NULL ,
				   password text NOT NULL ,
		           PRIMARY KEY ( id ));");
		echo "Created $tablename <br />\n";
		
		$db->query("CREATE index testINDEX on $tablename ( rand)");
		echo "Created index<br /> \n";
		
	} else {
                echo "$tablename and $dbname Already exists<br />\n";
	}
	// This kills the records
	$db->query("delete from $tablename");
	echo "All records deleted<br />\n";
	
        // This will begin the transaction and start throwing information into the database
	$db->beginTransaction();
	$n=1;
		
		
		$hashr = md5("1234");
		$sql="INSERT INTO $tablename ( id , username , password ) VALUES ($n, 'john', '$hashr' );";
		
                // this submits one query to be committed. Each line of code you need to redo this line below.
		$db->query($sql);
		
	// Once you have made all the queries you wanted this will make the actual changes to commit to the database.		
	$db->commit();
	

	echo "Test Data Insert Complete<br />\n";
echo "<table>\n";
} else {
	die($err);
}


// This is the selection query will then further below it will be displayed
$r = $db->query("select * from $tablename WHERE username LIKE 'john' and password LIKE '$hashr'");


        
// This fetches the data and then displays it in a table.
while ($res = $r->fetch(SQLITE_ASSOC)) {
	echo "<tr>";
	echo "<td>\n" . $res["id"]."\n</td><td>\n".$res["username"]."\n</td>"."\n</td><td>\n".$res["password"]."\n</td>";
	echo "</tr>\n";
	if(!isset($res['id'])) continue;  
	
}
echo "</table>";
echo "<br />";

// This takes the same Query and uses COUNT to count the records in the set.
$rowsc = $db->query("SELECT COUNT(*) as count FROM $tablename WHERE username LIKE 'john' and password LIKE '$hashr'");
$rowc = $rowsc->fetch(SQLITE_ASSOC);
$numRows = $rowc['count'];
echo $numRows;

?>