PHP password generator

Simple password generator class in PHP. Allow users to choose what kind of characters should be in the password

After long and hectic day with office work in the night I relax to do some coding (by the way I spend 80% of my office time doing coding :P). So, I decided to write a “Create Password” utility. This is just for the sake of code something because there are many fancy libraries for this purpose already available, as open source rocks!!!

First I thought what password could have, alphabets small and capital, number and special character but user must have flexibility to exclude any of this option so I came up with a class having all options.

 

abstract class Options
{	
	const SmallAlphabets = 0;
	const CapitalAlphabets = 1;
	const IsNumeric = 2;	
	const IsSpecialCharacters = 3;
}

I made it abstract, as I did not need to implement any function inside the class. It worked as enumeration.

Then I created a function to allow user to enable what options he wants and set options in constructor as the set on the generation of class object. User can omit code to disable any option

 

function UseInPassword($options){
/** set correponding bit value to 1 to keep track of allowed options */
$this->optionsTrack = $this->optionsTrack | pow(2,$options);
}

Here, I did a trick, I played with logical operators and I set the bit in an integer corresponding the value any option had in Options class.

GetPassword is the main function. User called that from outside. I wanted to generate all characters equally. For example, password length is 6 and user enable only SmallAlphabets, then 6 small alphabets will be created but if SmallAlphabets and IsNumeric is enabled then 3 small alphabets and there number. What if user enables all? There are four options and length is 6. 6 is not divisible by 4 so we cannot generate all options equally. We have to take reminder to generate more characters equal to reminder to fulfill password length. So each option generated once to make 4 characters and code will generate 2 more character in the sequence of their values in Options class. As follow

Count the options set by user by checking corresponding bit

 

for($i = 0 ; $i < 5 ; $i++){			
			$mask = $this->optionsTrack & pow(2,$i);
			if($mask > 0){
				$optionsCount++;
				$allowedOptions .= strval($i);
			}
		}


Get count of characters per option

 

$initialOptionCount = intval($this->passwordLength / $optionsCount);	
$reminder = $this->passwordLength % $optionsCount;	

Get final count as if password length is not completely divisible by the count of allowed option then we have to generate some character one more time

 

$finalOptionsCount = $initialOptionCount + ($i < $reminder ? 1 : 0);

Complete commented code is below and on git Hub and easy to understand.

Complete PHP code for Password generator

 

<?php
// namespacess
namespace junaid\code\pword\generator;

/** enumeration class to define what password would have and what would not have */
abstract class Options
{	
	const SmallAlphabets = 0;
	const CapitalAlphabets = 1;
	const IsNumeric = 2;	
	const IsSpecialCharacters = 3;
}


/** passsword generator class */
class Generator{
	
	public $passwordLength;
	public $optionsTrack;	
	
	/** below you can update a list of special character 	 
	 	and add or remove characters according to your will */ 
	private $specialCharacters = [
			'~','`','!','@','#','$','%',
			'^','&','*','(',')','-',
			'_','=','<','>',
			';',':','[',']','{','}'
	];
	
	function __construct(){
		$this->passwordLength = 7;
		$this->UseInPassword(Options::SmallAlphabets);
		$this->UseInPassword(Options::CapitalAlphabets);
		$this->UseInPassword(Options::IsNumeric);
		$this->UseInPassword(Options::IsSpecialCharacters);
	}
	
	/** enable different type of characters by passing corresponding Options value
	 	See in constructor how I enable all options by four calls of this function */
	function UseInPassword($options){
		/** set correponding bit value to 1 to keep track of allowed options */
		$this->optionsTrack = $this->optionsTrack | pow(2,$options);
	}
	
	function GetPassword(){
		if(0 == $this->optionsTrack)
			exit("No parameter set....");
		$optionsCount = null;
		$allowedOptions = "";
		
		/** count what are the options set by user by ANDing corresponding bit value with power of 2 */
		for($i = 0 ; $i < 5 ; $i++){			
			$mask = $this->optionsTrack & pow(2,$i);
			if($mask > 0){
				$optionsCount++;
				$allowedOptions .= strval($i);
			}
		}
		
		/** get count of characters per option need to be created */
		$initialOptionCount = intval($this->passwordLength / $optionsCount);		
		$reminder = $this->passwordLength % $optionsCount;
		
		$passwordArray = array();

		/** generate characters and put in array */
		for($i = 0 ; $i < strlen($allowedOptions) ; $i++){
			/** if provided lenght is not divisble by the count of allowed options
			  	some options need to be created more than other to get no of character 
			  	equal to password length */			
			$finalOptionsCount = $initialOptionCount + ($i < $reminder ? 1 : 0);
			
			for($j = 0 ; $j < $finalOptionsCount ; $j++){
				$passwordArray[] = $this->GetSingleCharacter($allowedOptions[$i]);
			}
		}
		
		/** shuffle */
		shuffle($passwordArray);
				
		return implode($passwordArray);
	}
	
	/** return character on the basis of provided option value */
	function GetSingleCharacter($switch)
	{
		$tmp;
		switch($switch){
			case Options::CapitalAlphabets:
				$tmp = chr(rand(65,90));
			break;
			case Options::SmallAlphabets:
				$tmp = chr(rand(97,122));
			break;
			case Options::IsNumeric:
				$tmp = rand(0,9);
			break;
			case Options::IsSpecialCharacters:
				$tmp = $this->specialCharacters[rand(0,sizeof($this->specialCharacters)-1)];
			break;
		}		
		return $tmp;
	}
	
	function __desctruct(){
	}
}


use junaid\code\pword\generator as ns;
$obj = new ns\Generator;
echo $obj->GetPassword();

?>


LeetCode – Check valid Sudoku in PHP

What is Sudoku

Everyone plays sudoku once in a while. It is a good time-pass. Logic is, Sudoku consist of 9 rows and 9 columns and 9 blocks. Each block contains 3 rows and 3 columns, means if you divide 9 rows into 3 parts and 9 columns into 3 parts, you would get 9 squares or blocks.

Any Sudoku, is provided with predefined values (ranges 1-9, inclusive) for some cells and some cells are empty. To finish Sudoku game, user has to be filled all empty cells with a numeric value ranges one to nine (inclusive), in a way that no row, column or block has duplicate value.

PHP Implementation

Following php code is for a problem from Leetcode to check if any provided Sudoku is valid or is it already has any duplicate value in any row, column or block.

 

<?php
/*
* checkValidSudoku
* Create by Junaid Hassan
* email : junaidhassanalvi@gmail.com
* Blog : junaidhassanalvi.wordpress.com
* Linkedin : http://linkedin/in/junaidhassanalvi
* Date : 22-dec-2015
*/

namespace JunaidHassan\ProgrammingProblems\LeetCode;

class checkValidSudoku
{
	var $sudoku = array();
	
	// take inputs
	function populateSudoku($input)
	{
		$this->sudoku = $input;
	}
	
	function validate()
	{
		$bitMap;
		
		//check all rows for duplicate values
		// any duplicate value in any row will fail validation
		for($raw = 0 ; $raw <9 ; $raw++){
			$bitMap = 0;			
			for($col = 0 ; $col <9 ; $col++){
				if('0' != $this->sudoku[$raw][$col]){		
					
					// calculate mask to get or set any particular bit from bitMap
					$mask = pow(2,$this->sudoku[$raw][$col]);					
					
					// check if a bit againt the value is already set to one, 
					// if it is already set,it means program already encounter the value, return false, 
					// else set it to one
					if(($bitMap & $mask) == 0)
					{
						$bitMap = $bitMap | $mask;
					}
					else
					{
						return false;						
					} 
				}
			}
		}		
		
		// check all columns for duplicate values
		// any duplicate value in any column will fail validation
		for($col = 0 ; $col <9 ; $col++){
			$bitMap = 0;
			for($raw = 0 ; $raw <9 ; $raw++){
				if('0' != $this->sudoku[$raw][$col]){	
					
					// calculate mask to get or set any particular bit from bitMap
					$mask = pow(2,$this->sudoku[$raw][$col]);
					
					// check if a bit againt the value is already set to one
					// if it is already set,it means program already encounter the value, return false, 
					// else set it to one
					if(($bitMap & $mask) == 0)
						$bitMap = $bitMap | $mask;
					else
						return false;
				}
			}
		}
		
		
		$xStart = 0;
		$yStart = 0;
		
		// check for 9 blocks
		// IN Sudoku, we have 9 blocks, each blocks contain 3 rows and 3 columns
		// any duplicate value in any block will fail validation
		for($b = 0 ; $b < 9 ; $b++){
			
			// set start x index and y index for every block according to block number
			$xStart = floor($b /3) * 3;
			$yStart = ($b % 3) * 3;
			$bitMap = 0;			
			
			// traverse through all rows in the block
			for($x = $xStart ; $x < $xStart + 3 ; $x++){
				// traverse through all columns in the block
				for($y = $yStart ; $y < $yStart + 3 ; $y++){	
					
					if('0' != $this->sudoku[$x][$y]){
						// calculate mask to get or set any particular bit from bitMap
						$mask = pow(2,$this->sudoku[$x][$y]);
						
						// check if a bit againt the value is already set to one
						// if it is already set,it means program already encounter the value, return false, 
						// else set it to one
						if(($bitMap & $mask) == 0)
							$bitMap = $bitMap | $mask;
						else
							return false;
					}
				}
			}
		}
		
		// if validate for all rows, columns and blocks are passed then Sudoku is valid
		return true;
	}
}

use \JunaidHassan\ProgrammingProblems\LeetCode\checkValidSudoku as validateSudoku;

$obj = new validateSudoku();

//define input
$input =  array(
	array(3,0,0,0,7,0,0,1,0), //1
	array(6,2,0,1,9,5,0,0,0), //2
	array(0,0,9,0,0,0,0,6,0), //3
	array(8,0,0,0,6,0,0,0,3), //4
	array(4,0,0,8,0,3,0,0,1), //5 
	array(7,0,0,0,2,0,0,0,6), //6
	array(0,6,0,0,0,0,2,8,0), //7
	array(0,0,0,4,1,7,0,0,5), //8
	array(1,0,0,0,8,0,0,7,9) //9
);

// set input
$obj->populateSudoku($input);

// validate
echo "Given Sudoku ".($obj->validate() ? "is" : "is not")." a valid Sudoku";

?>


Codeigniter with Model-View-Controller (MVC) architecture

Codeigniter with the power of MVC

PHP as being open source enjoys a lot of free available frameworks. Some are very huge and some are small. People adopt according to their needs.

I am very font of Codeigniter by Ellis Lab because sometime you have very strict timelines and you need Agile or rapid development. Here you feel a need for a framework that could be configure with zero or minimal configuration, and structured and complete enough to fulfill your requirements. So, Codeigniter is there to rescue.

For every framework, it is always considerable to choose best architecture for its organization, extensibility and management. Model-View-Controller MVC is the most popular among all for PHP.

To implement MVC in PHP, you have to have Object Oriented Programming (OOP) concepts which is out of the scope for this article. I am writing another article on that and will release soon.

Something about Model – View – Controller (MVC)

I will elaborate MVC implementation in codeigniter but first something about MVC

  • Controllers received all request from users and call models and views to render the information as directed in the request.
  • Models are modulation for any database or other system. Models do not play role in every request received by controllers. Actually controllers manage model when there is any change occurred in model. Views are not aware of any change in models, its controller responsibility to notify related views about the change.
  • Views are customized output representations, generated as per current models state and request sent to controller.

MVC is controlled and desired separation or abstraction for result outputs. User never has access to models or views, he/she only interact with controllers. Controllers are the component, which received calls, sends commands to models to know about its state, do any mention change in models, call views to tell about changes in models and render customized output for views according to direction provide in the call and current state of models. One controller can call many models and views.

There are many variations in MVC architecture. Google it to get it :). Now back to Codeigniter.

MVC in Codeigniter

This article is about codeigniter2.1.3 which is current stable version at this time. Codeigniter has very simple directory structure. In application folder, you create your web application. Inside application, controller will go to controllers folder, model to models folder and views to views folder. There are many other folders in application folder for many other purposes.

A big attraction for MVC in PHP is to handle web request smartly with SEO-friendly, User-friendly or clean URL.

Consider following request to Codeigniter web application

greyinfotech.com/index.php/users/update/97

After index.php, first parameter is controller name (users), second is function name inside controller (update) and last one is the parameter (97), which will be provided to the function in the controller.

With the help of some tweaks in your .htacess, you can get rid of index.php in above URL and can get neat and clean URL as follow

greyinfotech.com/users/update/97

Now a look on how models, views, controller are accessed in Codeigniter. There are some rules you have to follow to route the web request to correct controller. We will take about URL as an example.

  • There must be user.php in application/controllers folder.
  • User.php must have a class named Users (Note he first letter is capital here).
  • User class must be inherited by CI_Controller class( A parent controller class for all controllers).
  • Users class must have public function named update.
  • Update function must have a parameter, to which the last parameter (97) will be provided.

Function name and parameters are optional in URL. If function name is not provided, Codeigniter will take index as a function name by default. The number of parameters function has, the number of parameters you have to provide in the URL and they will be passed to the function’s parameters as they occurred in URL

Codeigniter load any model through model method of load object as follow

$this->load->model('Applicants_model');

After that you will have class level variable Applicants_model ($Applicants_model) which is the object for model class Applicants_model. Now you can call any method from Applicants_model class with the variable you got, as follow

$this->Applicants_model->insert();

To load Applicants_model

  • There must be applicants.php file in application/models folder.
  • applicants.php must contain Applicants_model class.
  • Applicants_model class must be inherited by CI_Model class (A parent model class for all models).
  • Applicants_model class must have function named insert.

Same for view, controllers can call view as follow

$this->load->view('applicants_view', $data);

Second parameter is an array of data that will be passed to the view. Second parameter is optional and if it is array it each key will be available as a variable in called view. Mainly its keys are extracted by PHP extract function.

To load applicants_view

  • There must be applicants_view.php file in application/views folder.

Architecture is, any web request received by be Codeigniter be directed to the controller specified in web request’s URL. This eliminates the direct access to models and views and make controllers the sole responsible to trigger and control all operations. Then, to handle operation for views and models, functionality is provided to controller to load any model and view for interaction. By loading any model, controller is now have rights to do any changes, get any information or check any expected changes. After that, controller can notify any view about this change, pass information to customize it as needed and render it as an output. Clearly model and views are unaware of each other, controller is the glue, which becomes middle-ware to transit any change between views and models.

I want to split this article in two articles, one of MVC and another is for Codeigniter, but then I decided that it should be better in this way.

MVC is architecture to control access and customized provided information in desired fashion. Codeigniter comply it very well and developers enjoy coding their application due to its simplicity and power of MVC.

Some useful functions for WordPress plugins development

A glance on wordpress plugins

WordPress is one of the popular CMS. I like it due to its simplicity. A person who does not know PHP programming can customized WordPress highly, from back-end. Along With, WordPress has lots of PHP classes and functions for PHP developer to show their magic.

WordPress is not an object-oriented paradigm. You occasionally can find classes but it does not have true concepts of object-oriented programming. You often just call functions to get your way. However, I believe, this thing make development in WordPress faster. Although, it lacks the organization of related methods and functionalities but still it is a charm for developers due to its ease.

Programming level customization normally done through plugins or you can say it is the best way to customize WordPress. There are tons of article on web about how to create plugin. In my article I will not focus on how plugin is developed but I will listed some useful functions for its development

WordPress plugins are normally easy to install. You just have to paste your plugin in wp-content/plugins folder and activate it through admin panel and it starts to work. Also WordPress has mechanism that help you to create plugin without changing the code for core libraries. They call it hooks. To know about hooks , read my another article, WordPress hooks – filters and actions.

Your plugin could be small as a single file and could be large as a folder contain lots of php, javascript, CSS files and images. All you have to do is to put following header, in a file you want to make entry point for your plugin. This file will be called on every page load in WordPress

/*
 *
 * 	Plugin Name: Greyinfotech Job Portal
 * 	Plugin URI: greyinfotech.com
 * 	Description: Job Manager for all jobs related operations.
 * 	Version: 1.0
 * 	Author: Junaid Hassan
 * 	Author URI: junaidhassanalvi.Wordpress.com/
 *
 */

All information is optional except Plugin Name. From here, WordPress recognizes that this is entry point for a plugin.

Function often used in WordPress plugins

Every plugin must contain two functions. One for activation, one for deactivation. You hook these two functions, to be called when plugin is activated or deactivated through admin panel as follow

register_activation_hook(__FILE__, 'activate');
register_deactivation_hook(__FILE__, deactivate');

Note that, these two functions must be in the same plugin file, which you define as an entry point. Following are few functions, commonly used in plugin.

In WordPress you have global array $wp_filter, this array can be manipulated to see all hooks added so far.

add_filter and add_action is used to add functionality into system without effecting core APIs and add_shortcode is to add something to html design at specific place. Following is the example of short code

add_shortcode('my_shotcodes', 'my_shotcodes_func');

With the help of add_shortcode you can add shortcode for my_shotcodes tag.. In html where you want to add your desire html in the post, you add following

[my _shotcodes ]

or

[my _shotcodes param1=”register” param2=”form”]

Above are two examples for shotcodes, both will execute function my_shotcodes_func and replace my_shotcodes tag with the response return by the my_shotcodes_func. Second example above also passing two parameters (param1 & param2) to my_shotcodes_func. The function will get these in a form of array. Param1 and param2 will be the keys of array.

Functions could be used, as per need

If you are creating your own tables in plugin, you have to use dbDelta. dbDelta is very handy as it Identifies difference between new and old version changes and update accordingly.

If you have your own custom roles then you have to use add_role / remove_role / get_role to add/ delete and retrieve information regarding the roles. Also with custom role, custom capabilities could be added to the system. add_cap / remove_cap used for this purpose.

Something you need to add a static page or post to show on the front-end. Here, wp_insert_post / wp_delete_post is very handy. You have to define attributes for a post in any array and pass to the wp_insert_post function. Following is an example

$_p = array();
$_p['post_title'] = __('Job listing');
$_p['post_status'] = 'publish';
$_p['post_type'] = 'page';
$_p['comment_status'] = 'closed';
$_p['ping_status'] = 'closed';
$_p['post_category'] = array(1);
$the_page_id = wp_insert_post($_p);

Above are the most common functions I have seen, to be used in plugins so far. However, thousands of plugins are available and every developer has its own approach. But it is always better to go for the best practices for any framework, also it is always better to comment and test your code thoroughly before publish.

WordPress hooks – filters and actions

A glance on WordPress hooks – filters and actions

WordPress has become far more popular than anyother blogging framework in a very short period of time. With the time, along with the popularity, it also extends. Tons of plugins are available on WordPress’ website.

WordPress provides very handy mechanism to extend functionality of wordpress with out messing-up with its core libraries. This thing is very helpful when you try to upgrade the version, as you do not have to remember what you changed. The objective to makes new changes separated from original code is achieved by a mechanism known as Hooks in WordPress terminology.

What is hook ?

There are two types of hooks. We will talk about later but first, what is hook? Named suggest, to hook something, to attach something, to tag something. Of course, it is used to attach some extra functionality with WordPress’ core behavior for any event. Instead of, introducing new code in core libraries of WordPress we write code separately in a file (that could be your plugin file in plugins folder) and attach the reference or hook the reference to that code in WordPress global hook list and call that code where you want it to be executed. Looks complicated? But it is not.

Types of hooks – action and filter

As I said, there are two types of hooks, Number one is filter and second one is action. Filter is when you want to modify something; it could be anything, any variable, any text which is going to be echoed. On the other side, action is when you want to run something entirely new. In other words, you passed some value to filter and it changes that value and pass back to you while to action you just call and it will perform something.

Ok, let understand filter first with example, we have two magic function add_filter and apply_filters

function modify_data(data) {
   return $data." Is passed on ".date('l jS \of F Y h:i:s A');
}

add_filter("my_hook","modify_data");

First argument is a unique identifier for your filter. You will call it through this identifier. Second is the name of function that we created. add_filter also has 2 other parameters, priority that describe the sequence in which all functions hooked with a single hook will be executed. Default value for priority is 10 but you can change as say. And second one is number of arguments passed to filter.

Ok, now simply where you want to execute that filter just call it with apply_filters like this

$data = apply_filters(("my_hook", $data );

As you can figure out the above statement, it is quite self-explanatory.

Similarly for action but here we want to start another process to do something. add_action and do_action are magic functions.

function email_friends( $post_ID )
{
   $friends = 'bob@example.org, susie@example.org';
   wp_mail( $friends, "sally's blog updated", 'I just put something on my blog: http://blog.example.com' );

   return $post_ID;
}
add_action('publish_post', 'email_friends');

Now you can call your action

do_action('publish_post' , 12);

You call the action by providing its unique identifier and the parameter required by function.

In the example for filter, we created our own hook that is my_hook but in action’s example we used a hook that is defined by WordPress already.
It elaborates that WordPress has defined many hooks for their system and if you exactly know what hook is required or where you want your code to be executed you can use pre-defined hook or you always free to create new one.

List of all hooks available on WordPress webiste

JSON (JavaScript Object Notation)

What is JSON ?

JSON is JavaScript Object Notation. This is a sub set of JavaScript. Those who are aware of JavaScript’s Objects will not find this thing new.
JSON has been adopting due to its easy to use and lightweight. Now almost every language has some set of functions to deal with JSON.

What is JSON usage ?

To communicate between two systems, we need a format or pattern that can be recognized by both systems. Still XML is using widely as an internationl standard to communicate between homogenous system. In middle-wares, web services, SOA (Service Oriented Architecture), XML is used as it has structured format and can be transmitted on network and can be read-able to all systems. JSON can also be used for this purpose.

So why JSON and why not XML ?

First, it is lightweight. XML become heavier doe to its tags. In addition, you have to traverse whole XML from top to reach any tag. It boosts the time required if you are looking for the tag that is in the bottom of xml. For this, you have to traverse whole XML.

JSON on the other hand parse to an object and now that object can be used to access information.

In PHP we have few functions for JSON. json_encode and json_decode could be used to encode and decode JSON message. json_encode convert provided array or object in a string that could be used later to again convert it to array through json_decode. As object or array is now string, therefore, it is easy to preserve or safe it.

JSON is also supported in Javascript.JSON.stringify and JSON.parse could be used to encode and decode string. Other programming languages also have their own functions.

JSON can be used to pass information from server-side scripting language to client-side scripting language for example, PHP and JavaScript. As it is support by both languages. Still, if any language does not native functions for JSON, small parser could be written, as it is just a string like XML and could be understood by any system.

JSON syntax

According to W3C, JSON can contain following values

  • String
  • Number
  • Boolean
  • NuLL
  • Object
  • Array

And guidelines are

  • All data is in a key value pairs form
  • Each key value pair is separated by comma
  • Objects are enclosed by curly brackets
  • Arrays are enclosed by square brackets

Now look to following JSON message

var class = [
				"Name" 			:	"First year",
				"Active" 		: 	true,
				"NoOfStudents" 	: 	200,
				"Prerequisite" 	: 	NULL,
				"Additional"	:	{"BatchNo" : "DA299", "Shift" : "Morning" } , 
				"YearCoverd" 	: 	[ 2009, 2010, 2011, 2012],
				"Teachers" 		: 	[
										{ "firstName" : "Bob" , "lastName" : "Williams" }, 
										{ "firstName" : "David" , "lastName" : "Brook" }, 
										{ "firstName" : "John" , "lastName" : "Hanks" }
									]
      		];

It describes the all. Additional is a Javascript object with contains other values BatchNo and Shift, that’s way it is enclosed by curly brackets. YearCoverd and Teachers are arrays. Teachers is the arrays of objects contain three elements while YearCoverd contain numbers. Objects and arrays can be nested up to the level you want and this makes JSON good structure.

var obj1= 	{
				arr1	[
						obj2	{
								arr2 	[
										obj3 	{
												arr3[ ……. ]
												}
										]
								}
						]
 			}