Difference between revisions of "PHP Login"

From KOP KB
Jump to: navigation, search
(PHP MyAdmin Create database)
 
(39 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
<html>
 +
<style>
 +
.mw-code{
 +
padding: 0.2em!important;
 +
border: none !important;
 +
}
 +
.border{
 +
border: 1px solid white;
 +
padding: 0.5em!important;
 +
background-color: #AAAAAA;
 +
}
 +
</style>
 +
</html>
  
 
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
 
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 ==
 
== PHP MyAdmin Create database ==
<syntaxhighlight lang="mysql">
 
CREATE TABLE `members` (
 
`id` int(4) NOT NULL auto_increment,
 
`username` varchar(65) NOT NULL default '',
 
`password` varchar(65) NOT NULL default '',
 
PRIMARY KEY (`id`)
 
) TYPE=MyISAM AUTO_INCREMENT=2 ;
 
  
--
+
<html>
-- Dumping data for table `members`
+
<iframe src="https://knightsofprocrastination.ca/KOPKB/phplogin.html" width="600px" height="330px">
--
+
</iframe>
 
+
</html>
-- use the md5 bracket to hash the passwords
 
-- create as many insert into commands as you need for how much
 
-- there could be other values as well depending on what is needed for login
 
INSERT INTO `members` VALUES (1, 'john', md5('1234'));
 
</syntaxhighlight>
 
  
 
== Setting up the First Page ==
 
== 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
 
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
<syntaxhighlight lang="php">
+
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
<?
 
<?
 
session_start();
 
session_start();
Line 70: Line 72:
 
</table>
 
</table>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</div>
  
 
== Checking the Login ==
 
== Checking the Login ==
<syntaxhighlight lang="php">
+
[[#top|Top of Page]]
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
<?php
 
<?php
 
$host="mysqlv105"; // Host name
 
$host="mysqlv105"; // Host name
Line 125: Line 130:
 
?>
 
?>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</div>
  
 
== Logged in Page ==
 
== Logged in Page ==
<syntaxhighlight lang="html4strict">
+
[[#top|Top of Page]]
 +
<div class="border">
 +
<syntaxhighlight lang="html4strict" enclose="div">
 
<html>
 
<html>
 
<header>
 
<header>
 
<script>
 
<script>
 +
</syntaxhighlight>
 +
<syntaxhighlight lang="javascript">
 
function listCookies() {
 
function listCookies() {
 
     var theCookies = document.cookie.split(';');
 
     var theCookies = document.cookie.split(';');
Line 158: Line 168:
  
 
if(sesscompa == ""){
 
if(sesscompa == ""){
window.location.assign("http://knightsofprocrastination.ca/phplogin/")
+
window.location.assign("http://domain.com/loginpage.php")
  
 
}else{
 
}else{
Line 164: Line 174:
 
     if(m == 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{
 
else{
window.location.assign("http://knightsofprocrastination.ca/phplogin/")
+
window.location.assign("http://domain.com/loginpage.php")
 
}
 
}
 
}else{
 
}else{
window.location.assign("http://knightsofprocrastination.ca/phplogin/")
+
window.location.assign("http://domain.com/loginpage.php")
 
}
 
}
 
}
 
}
 +
</syntaxhighlight>
 +
<syntaxhighlight lang="html4strict">
 
</script>
 
</script>
 
</header>
 
</header>
Line 180: Line 196:
 
</html>
 
</html>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</div>
  
 
== Another Method Sqlite ==
 
== Another Method Sqlite ==
Do to other servers not having the same means to do what you need with sqlite this is another method you can use to create passwords and so.
+
[[#top|Top of Page]]<br>
 +
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.
  
=== Starting off with starting up the db ===
+
=== The DB Construct ===
<syntaxhighlight lang="php">
+
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.
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
<?
 
<?
  
Line 196: Line 216:
 
       }
 
       }
 
   }
 
   }
 
+
</syntaxhighlight>
 +
</div>
 +
 
 +
=== 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.
 +
 
 +
<div class="border"  enclose="div">
 +
<syntaxhighlight lang="php"  enclose="div">
 
   $db = new MyDB();
 
   $db = new MyDB();
 
   if(!$db){
 
   if(!$db){
Line 215: Line 242:
 
   }
 
   }
 
   $db->close();
 
   $db->close();
 
+
</syntaxhighlight>
 +
</div>
 +
 
 +
=== Table Creation === 
 +
Nothing to complicated just using basic SQL to create the table.
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
   $db = new MyDB();
 
   $db = new MyDB();
 
   if(!$db){
 
   if(!$db){
Line 239: Line 272:
 
   $db->close();
 
   $db->close();
 
   //create finish
 
   //create finish
 
+
  </syntaxhighlight>
 +
</div>
 +
 
 +
=== Inserting the Data ===
 +
[[#top|Top of Page]]<br />
 +
Here were showing inserting just clear text but when you apply it you should hash it with md5 or stronger in your application.
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
   //insert start
 
   //insert start
 
    
 
    
Line 272: Line 312:
 
   $db->close();
 
   $db->close();
 
   //insert finish
 
   //insert finish
 +
</syntaxhighlight>
 +
</div>
  
    
+
=== 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.
 +
<div class="border">
 +
   <syntaxhighlight lang="php" enclose="div">
 
   //select start
 
   //select start
 
     $db = new MyDB();
 
     $db = new MyDB();
Line 281: Line 326:
 
       echo "Opened database successfully<br /><br />";
 
       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
 
   $sql =<<<EOF
 
       SELECT * from COMPANY where user like '%p%';
 
       SELECT * from COMPANY where user like '%p%';
Line 292: Line 337:
 
       echo "pass = ". $row['pass'] ."<br />";
 
       echo "pass = ". $row['pass'] ."<br />";
 
       echo  "<br />";
 
       echo  "<br />";
 +
        // Counter for amount of records it makes it important to ensure the correct person logged in
 
  $rc++;
 
  $rc++;
 
   }
 
   }
 
   echo "Operation done successfully<br /><br />";
 
   echo "Operation done successfully<br /><br />";
 
 
 
   //select finish
 
   //select finish
 +
$db->close();
 +
</syntaxhighlight>
 +
</div>
  
 +
=== Displaying the counter ===
 +
[[#top|Top of Page]]<br />
 +
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
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 
echo $rc;
 
echo $rc;
 
echo "<br /><br />";
 
echo "<br /><br />";
  
$db->close();
 
 
?>
 
?>
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
</div>
 +
 +
== 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.
 +
<div class="border">
 +
<syntaxhighlight lang="php" enclose="div">
 +
<?
 +
$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;
 +
 +
?>
 +
</syntaxhighlight>
 +
</div>

Latest revision as of 23:52, 10 December 2015

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;

?>