Thursday, 8 August 2013

User login with PHP/MySQL

Firstly, create a database entry and add a value to it:

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`)
    -> ) engine=MyISAM AUTO_INCREMENT=2 ;
Query OK, 0 rows affected (0.06 sec)

mysql> insert into members
    -> values
    -> (1, 'john', 'qwerty');
Query OK, 1 row affected (0.06 sec)

Secondly, use PHP to create a login screen:

<p align=center>You must login with the username and password to gain access:</p>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.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>

Thirdly, use a PHP to get username and password and compare with value in SQL:

<?php

session_start();
ob_start();

error_reporting(E_ALL);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="test"; // 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");

// Define $myusername and $mypassword
$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);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$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"
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
//header("location:login_success.php");
echo '<meta http-equiv="refresh" content="0;url=login_success.php">';
}
else {
//echo "Wrong Username or Password";
echo '<meta http-equiv="refresh" content="0;url=main_login.php">';
}
ob_end_flush();
?>

In the login_success.php, you can do any web page design:

<?php
// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
session_start();
echo $_SESSION['myusername'];
if(isset($_SESSION['myusername'])){
  //header("location:main_login.php");
  } else {
   echo '<meta http-equiv="refresh" content="0;url=main_login.php">';
}
?>

<html>
<body>
<b>Login Successful.</b><br>
Please click this to  <a href=logout.php>logout</a>
</body>
</html>

The logout.php is simple:

<?php
// Put this code in first line of web page.
print "logout";
session_start();
session_destroy();
?>
<p>Please click this to  <a href=main_login.php>login</a></p>

Now we will see how to encrypt the password.

Encrypt password with php

$password="john856";
$encrypt_password=md5($password);
echo $encrypt_password;
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$result=mysql_query($sql);

Sunday, 4 August 2013

PHP push message to browser client

Server Sent Events implementation using PHP

In the PHP script, named it server_msg01.php:
1) Content-Type set to text/event-stream
2) using a forever loop to keep on running
3) call set_time_limit(0) to run forever

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}

while(true) {
  set_time_limit(0);
  $serverTime = time();
  sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
  sleep(10);
}
?>

In the html file:
1) In the javascript, create a new EventSource with filename set to the PHP script filename.
2) use div element to display the output

<html>
<head>
<script>
function init() {

    var source;
    if (!!window.EventSource) {
        source = new EventSource('server_msg01.php');
        source.addEventListener('message', function(e) {
            document.getElementById('output').innerHTML += e.data + '<br />';
        }, false);
        source.addEventListener('open', function(e) {
            document.getElementById('output').innerHTML += 'connection opened<br />';
        }, false);
        source.addEventListener('error', function(e) {
 if(document.getElementById("output") != null)
 {
            document.getElementById('output').innerHTML += 'error<br />';
 }
        }, false);
    }
    else {
        alert("Browser doesn't support Server-Sent Events");
    }
}
</script>
</head>
<body onload="init()">

hello world.

<p><div id="output"></div></p>
</body>
</html>