Saturday 30 June 2012

PHP Login Script

0 comments



This requires 2 php files to be created -
1) Login.php
2) MyAccount.php


How this work -
When the user registers' with suitable username and password and uses this user details for logging in, the user is redirected to their account. If the username and password entered in incorrect, it displays an error message.


Login.php


############### CODE STARTS BELOW ###############


<?php 
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
//print_r($_POST);
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'@') === false) {
    $user_cond = "user_name='$user_email'";
} else {
      $user_cond = "user_email='$user_email'";    
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE 
           $user_cond
AND `banned` = '0'
") or die (mysql_error()); 
$num = mysql_num_rows($result);
  // Match row found with more than 1 results  - the user is authenticated. 
    if ( $num > 0 ) { 
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}  
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) { 
if(empty($err)){
     // this sets session and logs user in  
       session_start();
  session_regenerate_id (true); //prevent against session fixation attacks.
  // this sets variables in the session 
$_SESSION['user_id']= $id;  
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie 
  if(isset($_POST['remember'])){
 setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
 //setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
 setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
  }
 header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
 }
} 
?>




//PHP Script ends above
//Below is the HTML form





<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  
  <tr> 
    <td width="160" valign="top"></td>
    <td width="732" valign="top"><p>&nbsp;</p>
      <div class="fleft paddr10" style="width:74%;text-align:justify;">


</div>  
 <p>
 <?php
 /******************** ERROR MESSAGES*************************************************
 This code is to show error messages 
 **************************************************************************/
 if(!empty($err))  {
  echo "<div class=\"msg\">";
 foreach ($err as $e) {
   echo "$e <br>";
   }
 echo "</div>";
  }
 /******************************* END ********************************/  
 ?></p>
      <form action="login.php" method="post" name="logForm" id="logForm">
        <table width="85%" border="0" cellpadding="4" cellspacing="4" class="loginform" style = "margin-left: -168px;">
          <tr> 
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr> 
            <td width="28%">Username / Email:</td>
            <td width="72%"><input name="usr_email" type="text" class="required" id="txtbox" size="25"></td>
          </tr>
          <tr> 
            <td><br/>Password:</td>
            <td><br/><input name="pwd" type="password" class="required password" id="txtbox" size="25"><a href="forgot.php"><font color="#0c80af" size= "2">&nbsp;&nbsp;&nbsp;&nbsp;     Forgot Password?</font></a>  
                  </td>
          </tr>
          <tr> 
            <td colspan="2"><div align="center" style="margin-left: 170px;">
                <br/><input name="remember" type="checkbox" id="remember" value="1" style="font-size:15px;">
                <font size="2" color="000000">&nbsp;&nbsp;Remember me</font></div></td>
          </tr>
          <tr> 
            <td colspan="2"> <div align="center"> 
                <p style="margin-left: 170px;"> 
                  <br/><input name="doLogin" type="image" id="doLogin3" value="Login" src="./images/login-now.gif">
 
 <br/>
                </p><br/>
                <p style="margin-left: 170px;"><font size="2" color="000000">New User? </font><a href="register.php"><font size="2" color="0c80af">Register Now >></font></a> 
                  </p><br/>
                <p style="margin-left: 170px;"><span style="font: normal 9px verdana">Powered by Parag/Anuja/Sonali<br/></span></p><br/>
<p><span style="font-size: 12px; margin-left: 170px;"><a href=index3.php><h6 style="margin-left:170px"><font size="2" color="000000"><< Back</font></div></td></h6></a></span></p>
              </div></td>
          </tr>
        </table>
        <div align="center"></div>
        <p align="center">&nbsp; </p>
      </form>
      <p>&nbsp;</p>
  
      </td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
</table>


################# CODE ENDS ABOVE #################




MyAccount.php

############### CODE STARTS BELOW ################

<?php 
include 'dbc.php';
page_protect();
?>


<html>
<head>
<title>My Account</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr> 
    <td width="160" valign="top">
<?php 
/*********************** MYACCOUNT MENU ****************************
This code shows my account menu only to logged in users. 
Copy this code till END and place it in a new html or php where
you want to show myaccount options. This is only visible to logged in users
*******************************************************************/
if (isset($_SESSION['user_id'])) {?>
<div class="myaccount">
  <p><strong>My Account</strong></p>
  <a href="myaccount.php">My Account</a><br>
  <a href="mysettings.php">Settings</a><br>
    <a href="logout.php">Logout </a>
  <p>You can add more links here for users</p></div>
<?php }
if (checkAdmin()) {
/*******************************END**************************/
?>
      <p> <a href="admin.php">Admin CP </a></p>
 <?php } ?>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p></td>
    <td width="732" valign="top"><p>&nbsp;</p>
      <h3 class="titlehdr">Welcome <?php echo $_SESSION['user_name'];?></h3>  
 <?php
      if (isset($_GET['msg'])) {
 echo "<div class=\"error\">$_GET[msg]</div>";
 }
   
 ?>
      <p>This is the my account page</p>

 
      </td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
</table>

</body>
</html>

################# CODE ENDS ABOVE #################


NOTE: The above scripts doesn't carry every scripts viz. admin.php, thankyou.php, etc. Also it does not include the designing scripts i.e the CSS script. Hence only using the above code won't help you in performing the login script page. Therefore, you can download the whole script package here!



Continue reading →

Database Connectivity Script in PHP

0 comments

Steps:

1) Copy the below code, open any text editor viz. Notepad++ and save as dbc.php

2) Set values inside the quotes for your MySQL settings.
    - database name
    - database user
    - database password

you will get these information from your hosting provider. Make sure you give full access rights to the database user. If you have cpanel, just login and create database and database user.

example:
define ("DB_HOST", "xxxxx"); // set database host
define ("DB_USER", "xxxx"); // set database user
define ("DB_PASS","xxxx"); // set database password
define ("DB_NAME","xxxx"); // set database name

3) Setting up reCaptcha for your Script:


   (i) Download recaptcha php library (http://recaptcha.net/plugins/php/), unzip and copy the single php file recaptchalib.php into login script folder. This is very important, without which the login script will not work.

   (ii) Go to recaptcha.net, register a free account, and you will get public and private keys. Make a note of that and set it here inside dbc.php
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxx";


4) Configuration settings:

(i) Automatic or Manual registration

/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1; // set 0 or 1

(ii) Other Settings (optional only)
These are the other settings in the script if you want you can change it like cookie expiry time, specify admin levels and much more..

define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password




****************CODE BEGINS BELOW**********************


<?php
/************* MYSQL DATABASE SETTINGS *****************
1. Specify Database name in $dbname
2. MySQL host (localhost or remotehost)
3. MySQL user name with ALL previleges assigned.
4. MySQL password
Note: If you use cpanel, the name will be like account_database
*************************************************************/
define ("DB_HOST", "xxxxxx"); // set database host
define ("DB_USER", "xxxxxx"); // set database user
define ("DB_PASS","xxxxxx"); // set database password
define ("DB_NAME","xxxxx"); // set database name
error_reporting(E_ALL ^ E_NOTICE);
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
/* Registration Type (Automatic or Manual) 
 1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
 0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1;  // set 0 or 1
define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
//define ("ADMIN_NAME", "admin"); // sp
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
/*************** reCAPTCHA KEYS****************/
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/**** PAGE PROTECT CODE  ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/
function page_protect() {
session_start();
global $db; 
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT'])){
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        logout();
        exit;
    }
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) ) 
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id  = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey)  ) {
 session_regenerate_id(); //against session fixation attacks.
 $_SESSION['user_id'] = $_COOKIE['user_id'];
 $_SESSION['user_name'] = $_COOKIE['user_name'];
/* query user level from database instead of storing in cookies */
 list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));
 $_SESSION['user_level'] = $user_level;
 $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);   
  } else {
  logout();
  }
  } else {
header("Location: login.php");
exit();
}
}
}
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len) 
{
    if (strlen($str) < $len)
        return $str;
    $str = substr($str,0,$len);
    if ($spc_pos = strrpos($str," "))
            $str = substr($str,0,$spc_pos);
    return $str . "...";
}
function isEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
return true;
} else {
return false;
}
 } 
function isURL($url) 
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}

function checkPwd($x,$y) 
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }


if (strcmp($x,$y) != 0) {
 return false;
 } 
return true;
}
function GenPwd($length = 7)
{
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
  
  $i = 0; 
    
  while ($i < $length) {    
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }
  }
  return $password;
}
function GenKey($length = 7)
{
  $password = "";
  $possible = "0123456789abcdefghijkmnopqrstuvwxyz"; 
  $i = 0;   
  while ($i < $length) {  
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);         
    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }
  }
  return $password;
}
function logout()
{
global $db;
session_start();
if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users` 
set `ckey`= '', `ctime`= '' 
where `id`='$_SESSION[user_id]' OR  `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}
/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy(); 
/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
header("Location: login.php");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
    if ($salt === null)     {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else     {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($pwd . $salt);
}
function checkAdmin() {


if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
?>


*******************CODE ENDS ABOVE*************************





Continue reading →
Friday 29 June 2012

PHP Captcha Code

0 comments

In this tutorial I will explain how to create a Captcha in PHP. We are using some of the features available in PHP for creating an image. This is very simple and basic tutorial and we are not using any custom fonts for generating captcha image. And we know that captcha code used to avoid spam/abuse or auto-submission.


       Flickr Like Edit Title


Captcha.php
<?php
session_start();
$ranStr = md5(microtime());
$ranStr = substr($ranStr, 0, 6);
$_SESSION['cap_code'] = $ranStr;
$newImage = imagecreatefromjpeg("cap_bg.jpg");
$txtColor = imagecolorallocate($newImage, 00, 0);
imagestring($newImage, 555, $ranStr, $txtColor);
header("Content-type: image/jpeg");
imagejpeg($newImage);
?>

Verifying captcha code is equal or not
Here we are storing a captcha code in SESSION variable and while verifying we have to compare the session variable with user entered data.
$_SESSION['cap_code'] - is having actual captcha code
$_POST['captcha'] - user entered captcha code
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($_POST['captcha'] == $_SESSION['cap_code'])
{
// Captcha verification is Correct. Do something here!
}
else 
{
// Captcha verification is wrong. Take other action
}
}
?>

Read This
The below html/CSS/Jquery code I used is just for an extra enhancement only and all the code is not needed actually. The above code is enough to check whether Human Verification is correct or wrong.

index.php
Contains HTML and PHP code. Image scr='captcha.php'
<?php
session_start();
$cap = 'notEq'; // This php variable is passed to jquery variable to show alert
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($_POST['captcha'] == $_SESSION['cap_code'])
{
// Captcha verification is Correct. Do something here!
$cap = 'Eq';
}
else
{
// Captcha verification is wrong. Take other action
$cap = '';
}
}
?>
<html>
<body>
<form action="" method="post">
<label>Name:</label><br/>
<input type="text" name="name" id="name"/>
<label>Message:</label><br/>
<textarea name="msg" id="msg"></textarea>
<label>Enter the contents of image</label>
<input type="text" name="captcha" id="captcha" />
<img src='captcha.php' />
<input type="submit" value="Submit" id="submit"/>
</form>
<div class="cap_status"></div>
</body>
</html>

Javascript
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js
"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function()
{
var name = $('#name').val();
var msg = $('#msg').val();
var captcha = $('#captcha').val();
if( name.length == 0)
{
$('#name').addClass('error');
}
else
{
$('#name').removeClass('error');
}
if( msg.length == 0)
{
$('#msg').addClass('error');
}
else
{
$('#msg').removeClass('error');
}
if( captcha.length == 0)
{
$('#captcha').addClass('error');
}
else
{
$('#captcha').removeClass('error');
}
if(name.length != 0 && msg.length != 0 && captcha.length != 0)
{
return true;
}
return false;
});
var capch = '<?php echo $cap; ?>';
if(capch != 'notEq')
{
if(capch == 'Eq')
{
$('.cap_status').html("Your form is successfully Submitted").fadeIn('slow').delay(3000).fadeOut('slow');
}
else
{
$('.cap_status').html("Human verification Wrong!").addClass('cap_status_error').fadeIn('slow');
}
}
});
</script>


CSS
body{
width: 600px;
margin: 0 auto;
padding: 0;
}

#form{
margin-top: 100px;
width: 350px;
outline: 5px solid #d0ebfe;
border: 1px solid #bae0fb;
padding: 10px;
}

#form label
{
font:bold 11px arial;
color: #565656;
padding-left: 1px;
}

#form label.mandat
{
color: #f00;
}

#form input[type="text"]
{
height: 30px;
margin-bottom: 8px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}

#form textarea
{
width: 340px;
height: 80px;
resize: none;
margin: 0 0 8px 1px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}

#form img
{
margin-bottom: 8px;
}

#form input[type="submit"]
{
background-color: #0064aa;
border: none;
color: #fff;
padding: 5px 8px;
cursor: pointer;
font:bold 12px arial;
}

.error
{
border: 1px solid red;
}

.cap_status
{
width: 350px;
padding: 10px;
font: 14px arial;
color: #fff;
background-color: #10853f;
display: none;
}

.cap_status_error
{
background-color: #bd0808;
}


Continue reading →
Friday 8 June 2012

Google acquires "Quickoffice" - the maker of mobile office suite for Smartphone and Tablets

0 comments

   

Google announced that it has get over on one of the top creators of office applications for mobile devices. The  “Quickoffice” is a office suite that are pre-installed on mobile devices from some of the most popular smartphone sold viz. Samsung, HTC, Nokia, LG, Sony, Motorola etc. The application has been installed on over 300 million devices to the date, the company claims. The Quickoffice suite application is available for iOS, Android and Sybian devices.  Adding up to the pre-installed suite on some phones, the company also claims its two main products called “Quickoffice Pro” and “Quickoffice Pro HD” are among the top-ten paid apps in the Google Play market.

Quickoffice is an assortment of apps for creating, editing and sharing Microsoft Office documents such as Word, Excel and Powerpoint. Google alleged in a statement that it will convey the office technology to its Apps product suite.

Google complete statement is:

We're happy to announce that we have acquired Quickoffice, a leader in office productivity solutions.

Google + Quickoffice = get more done anytime, anywhere

Today, consumers, businesses and schools use Google Apps to get stuff done from anywhere, with anyone and on any device. Quickoffice has an established track record of enabling seamless interoperability with popular file formats, and we'll be working on bringing their powerful technology to our Apps product suite.

Quickoffice has a strong base of users, and we look forward to supporting them while we work on an even more seamless, intuitive and integrated experience.

We're excited to welcome the Quickoffice team and their users to Google.



Continue reading →