Login Script for Your Website
One of the biggest challenges i had when first learning PHP was how to create a log in script. I had to get user input, interact with a database, process the user’s input and return a result. To me at the time this was very difficult. But now that have done it a couple of times, it is had become easy. My first approach was to have a PHP page itself that would handle the use case. But then i realized that it would be much easier to design a class to represent the use case. The class i designed is called login which extends from another class called signup.
<?php
require_once("../config.php");
require_once("class_signup.php");
class login extends signup{
private $_password;
private $_username;
private $_db_link;
function __construct(){
$this->connect_database();
}//end class constructor
function __destruct(){
$this->_db_link=NULL;
}//ebd destructor
public function connect_database(){
if(!$link = mysql_connect(_HOST_NAME_,_USERNAME_,_DBS_PASSOWRD_)){
print mysql_error();
$this->_sign_up_err=TRUE;
exit;
}//end if
$this->_db_link=$link;
}//end connect_database function
public function _validate_login($username,$password){
$this->_password=base64_encode($password);
$this->_username=$username;
$sql_statement="SELECT * FROM " ._DATABASE_NAME_. "."._USERS_TABLE_.
" WHERE username='$this->_username' AND password='$this->_password'";
if(!mysql_query($sql_statement,$this->_db_link)){//execut the msql query on the database
print mysql_error();
exit();
}
$sql_result=mysql_query($sql_statement,$this->_db_link);
if(mysql_num_rows($sql_result)!=0){
$sql_result=mysql_query($sql_statement,$this->_db_link);
$aRow=mysql_fetch_array($sql_result);
if($aRow['username']==$this->_username&&base64_decode($aRow['password'])==base64_decode($this->_password)){
$this->_log_user_in($this->_username,$this->_db_link);
}else{
header("Location: ".str_replace("index.php","",$_SERVER['HTTP_REFFERER'])."?error=true");
}//end else
}else{
header("Location: ".str_replace("index.php","",$_SERVER['HTTP_REFFERER'])."?error=true");
}//end else
}//end function
}
?><!--End php script-->
At the top of your log in page, after including the PHP file that holds the class definition, instantiate a login class like $login = new loin(); After this, you will have access to all the class’s functionalites. In the log in form, submit the page to itself with the POST method, ( action=”<?=$_SERVER['PHP_SELF'] ?>”, method=”POST”) . Call the member function _validate_login($username,$password) and pass it the username and password values that were sent in the $_POST array. Assuming that the u have a operable mysql database, the script will retrieve the values from the database then try to match them with the user’s inoput. If successful, the script will call a member function which it inherited from its base class ‘signup’. If the login fails for any reason, the script will redirect the user to the log in page with the query string “?error=true”. In my log in page, there is a script that checks this value and if it is set to true then it will display a message alerting the user that the username and or password were incorrect. Below is the member functin which the clas login has inherited to complete the use case.
public function _log_user_in($username,$dblink){
if(isset($dblink)){
$this->_db_link=$dblink;
}//end if
$sqlStatement="SELECT id FROM " ._DATABASE_NAME_. "."._USERS_TABLE_."
WHERE username='$username'";
if(!mysql_query($sqlStatement,$this->_db_link)){
print mysql_error();
exit;
}//end if
$sql_result=mysql_query($sqlStatement,$this->_db_link);
$aRow=mysql_fetch_array($sql_result);
session_save_path(_SESSION_SAVE_PATH_);
session_start();
session_set_cookie_params(3600000);//set the time lapse for tht cookies
$_SESSION['username']=$username;
$_SESSION['user_id']= $aRow['id'];
$user = new user();
$user->_increment_user_visits();
header("Location: ../");//rediret user to the homepage now that he r she has logged in successfully
}//end function
the script will simply set all the session values for the current user by retrieving it from the database and setting them in the $_SESSION array. it then redirects the user to the home page of the websites. I hope this was use full to those new to PHP programming.
remove_user_directory($dir_path)
The following is a PHP function that allows u to delete all the files in a specific directory and then the directory itself. Simply pass it the absolute (and i think relative path may work as well, well yeah..) of the directory.I wrote it because i couldn’t find a function to do exactly that. Its name is remove_user_directory because i initially wanted it to remove a user’s files from the system. but you can change the name and modify it if u like. I Will further improve on it so that it removes recursively. That should be somewhat tedious. : (
function remove_user_directory($dir_path){
$flag=TRUE;//will be returned
if(!is_dir($dir_path)){$flag = false;}
else{
$dir_path_sub_files = array();
$dir_path_sub_files = scandir($dir_path);
$number_of_files = count($dir_path_sub_files);
if($number_of_files!=0){
foreach(glob($dir_path . "*.*") as $filename){
if($filename!="."&&$filename!=".."){ unlink($filename);}
}
}//end if
rmdir($dir_path);//remove the empty directory
}//end else statement
return $flag;
}
getElapsedTime($timeStamp)
The following is a PHP function i constructed while working on a website. It i used to get the time that has elapsed from a timestamp that is passed to it and the current time-stamp. Fell free to use it in your own projects
//return type – string
//return examle – 3 weeks ago, 1 day 5 hours ago.
<?
function getElapsedTime($timeStamp,$precision){
$anArray = array();
$anArray[0]['name']="Year";
$anArray[0]['value']=31556926;
$anArray[1]['name']="Month";
$anArray[1]['value']=2629743.83;
$anArray[2]['name']="Week";
$anArray[2]['value']=604800;
$anArray[3]['name']="Day";
$anArray[3]['value']=86400;
$anArray[4]['name']="Hour";
$anArray[4]['value']=3600;
$anArray[5]['name']="Minute";
$anArray[5]['value']=60;
$anArray[6]['name']="Second";
$anArray[6]['value']=1;
$elapseArray = array();
$timeDifference=time()-$timeStamp;
$tempInt=0;
$i=0;
foreach($anArray as $anElement){
if(($timeDifference/$anElement['value'])>0){
$tempInt=$timeDifference/$anElement['value'];
$tempInt=(int)$tempInt;
if($tempInt==1){
$elapseArray[$i]['name']=$anElement['name'];
$elapseArray[$i]['value']=$tempInt;
}elseif($tempInt>1){
$elapseArray[$i]['name']=$anElement['name']."s";
$elapseArray[$i]['value']=$tempInt;
}
$timeDifference -=($tempInt*$anElement['value']);
$tempInt=0;
}
$i++;
}
$elapseArray["elased_time_string"]="";
$i=0;
foreach($elapseArray as $anElement){
$elapseArray["elased_time_string"].=$anElement['value']."
".$anElement['name']." ";
if($i==$precision){ break; }
$i++;
}
$elapseArray["elased_time_string"].="ago";
return $elapseArray["elased_time_string"];
}
?>