27 September, 2010

How to remove non-ascii characters from string

There is a simple way to remove non-ascii characters from a string. This can be used to filter values from POST variables as well. Following line of code does the thing.

$string = "This is a test É";
//replace the non-ascii characters from string with nothing i.e. remove
preg_replace('/[^(\x20-\x7F]*/','',$string);
echo $string;

23 September, 2010

Regular Expressions using Javascript

Sometimes regular expressions can be confusing, but they are great tools for matching a string against a character pattern. They are used for validation of user entry or changing the document content. You can replace a 40 line if/else code with just one line of regular expression. For starters, regular expressions can be fear striking but as you move on with the flow its keeps of getting more and more interesting.
Different languages support regular expressions and they are not as tough as they seem at first sight. Many languages support "find" ,"replace" and "search" feature in regular expressions.
So in this article i will be writing about regular expressions using javascript, to the point that I am also informed to.
Basic Syntax
Let's say you want to search for a string "rain" in a text. You can use two different formats for this.
First is using String Notation


var srchFor = /rain/; //do not use quotation marks
//Second is Object Constructor
var srchFor = new RegExp('rain');
//You can check this as follows:
var str = "When will it rain";
alert(srchFor.test(str));


The expression can be checked using match(), test(), search() or exec() method, all of these are listed later.
Let's say now you want to match a word that starts with some string, in this case, 'rain', you can check this by:


var srchFor = /^rain/;
var srchFor = new RegExp('^rain');
//Or you want to match a word that has just some string and en, in this case, has only 'rain' in it:
var srchFor = /^rain$/;
var srchFor = new RegExp('^rain$');


Here, ^ and $ are starting and ending indicator respectively.
And if want to match a word that ends with some string, in this case 'rain', then


var srchFor = /rain$/;
//Case sensitivity can also be checked. Like,
//if you want to find a word that ends with 'rain' regardless of the case,
//then:
var srchFor = /rain$/i; //Here i refers to case-insensitive
var srchFor = new RegExp('rain$', 'i');


Lets, say we have string that have the word 'rain' several times, now if we want to match a word that is repeated several times, then we can add a global
parameter 'g', doing this will return the matches as array. Such as:

var srchFor = /rain/g; //g refers to global


By default regular expressions match patterns only in single-line strings, so if we want to have a match for multiline strings using regular expressions then 'm' can be used. Such as,

var srchFor = /rain/m; //This matches for rain in multiline

And the parameters can be used in conjunction as well, like,

var srchFor = /rain/igm; OR /rain/gim OR /rain/min; etc in any order

So the above pattern matches 'rain' in multiline,regardless of case and returns array.

Period Character (.)
The dot character means match anything. Such as, match a string that has r at beginning and n at end. Such as,

var srchFor = /r.n/;

The above pattern matches 'ran', 'rin', 'ron', or even r#n or r n, etc.
However you can limt your choices by using square brackets, like

var srchFor = /r[au]n/;

The above pattern matches 'ran' or 'run'.
Exclude you choice, such as match a string excluding some , such as if you want to exclude 'ran' from searcgh then, do the following,

var srchFor = /r[^a]n/;
//But the square brackets match only one character at a time,
//so if you want to match multiple characters then pipes can be used,
var srchFor = /r(^a|u|i|eig|e)/;

This matches 'run', 'rin', 'reigh' and 'ren' but does not match 'ran'.

Escaping Characters
Certain characters need to be escaped, such as: +, /, -, (, ), *, {, }, and ?
Such as /r.n/ matches ran, run, but /r\.n/ only matches "r.n".
Lets us say, you want to validate email address using regular expression, then do the following:


var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;


In above case,
\W is shortcut for [^a-zA-Z0-9_]; match characters that have a to Z characters or 0 to 9 and underscore.
+ means 1 or more times possible
* means 0 or more times possible
? means 0 or 1 times possible
{n} means n times possible
{n,m} means n to m times possible
So,

var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;

/^[\W]+(\.[\W]+)* matches sudhi, or sudhi.test
then add @ symbol, then
([\W]+\.) matches oncemore, oncemore.co
then add dot (.),
[a-z]{2,7} means 2 to 7 times the a-z characters are possible.
Other shortcuts are
\d means [0-9] Only integers
\D means [^0-9] All characters but integers
\w means [a-zA-Z0-9_] All alphanumeric characters and the underscore
\W means [^a-zA-Z0-9_] All nonalphanumeric characters
\b means N/A Word boundary
\B means N/A Not word boundary
\s means [\t\n\r\f\v] All whitespace
\S means [^\t\n\r\f\v] No whitespace

Methods Using Regular Expressions
There are several methods that take regular expressions as parameters. The expression itself—
the things inside the slashes or the RegExp constructor—is called a pattern, as it matches what
you want to retrieve or test for.
• pattern.test(string): Returns true or false depending on whether it matches the string
• pattern.exec(string): Returns array on finding match
• string.match(pattern): Returns array of strings on finding match
• string.search(pattern): Matches the string and the pattern and returns the positions and returns -1 if not found
• string.replace(pattern, replaceString): Matches the string against the pattern and replaces every positive match with replaceString.
• string.split(pattern, limit): Matches the string against the pattern and splits it into array



So, Regular expressions only match characters; you cannot do calculations with them. And they are language independent.

22 September, 2010

Map Objects to Database in PHP

Data Mapper Pattern
Since code and database change occurs often during development stage, the separation between domain code and database tends to be beneficial, so that change
in one does not create a need to change the other. There exists a pattern using which we can map objects to database. One probable solution for this can be a
Data Mapper Pattern.
A general idea of the mapper pattern is that a class translates attributes (properties) and methods of domain code to database fields and vice-versa.
Data Mapper is responsible for routing information between domain code and database, creating new domain objects depending on information from database and
updating/deleting information from database depending on information from domain objects.
The mapping between object-oriented code and database can be done in different ways. It can be extracted from XML files, extracting from php array in the class
itself, or hand-coding the correlation in Data Mapper Class. This way implementation of mapping php objects to database is relatively simpler.
Let’s consider an analogy; we have a problem domain for storing user information. So we would generally have two classes; User and UserMapper. So applying the
Data Mapper Pattern we can handle the mapping of objects of User class with database tables and columns using UserMapper Class. For this case we could use an
XML configuration file implementation.
In following xml file, we have “user" as root element that contains a series of field elements as shown below:



id
getId
setId


title
getTitle
setTitle


name
getName
setName



Save the file as uers.xml
The 'name' elements are actually the physical database field name. The .... holds a method "getTitle" to extract attributes.
And .... element holds User method to use when populating the object values. Information regarding creating table structure can also be
added in the xml configuration file, such as type and size of the field. Such information can be particularyl userful when we are creating some kind of
packaged installation script. The information can be used to dynamically create SQL to create database tables. This users.xml file can be read and parsed using
PHP5's SimpleXML functions, like

simplexml_load_file("users.xml");

This XML configuration file will be read by our UserMapper class which acts as Data Mapper in this case. Since Data Mapper Pattern is unobtrusive in nature,
the domain object (User class in this case) remains competely unaware to Data Mapper's (UserMapper Class in this case) existence and due to this reason all the
domain objects (methods) must provided public access to the Data Mapper. In following example, we have Users class, that have all protected attributes but
provides 'get' and 'set ' methods.
Following is our sample Users.php Class

class User {
protected $id;
protected $title;
public function setId($id) {
if (!$this->id) {
$this->id = $id;
}
}
//the following function is called whenever an undefined instance method is called
//name of missing method is passed as first parameter and method arguments as second parameter
public function __call($name, $args) {
if (preg_match("/^(get|set)(\w+)/", strtolower($name), $match)
&& $attribute = $this->validateAttribute($match[2])) {
if ("get" == $match[1]) {
return $this->$attribute;
} else {
$this->$attribute = $args[0];
}
} else {
throw new Exception(
"Undefined method User::".$name."()");
}
}
protected function validateAttribute($name) {
if (in_array(strtolower($name),
array_keys(get_class_vars(get_class($this))))) {
return strtolower($name);
}
}
public function fetch() {
return $this->title;
}
}

And following is our Data Mapper Class

class UserMapper {
protected $conn;
const INSERT_SQL = " insert into users (title, name) values (?, ?)";
const UPDATE_SQL = "update users set title = ?, name = ? where id = ? ";

public function __construct($conn) {
$this->conn = $conn;
foreach(simplexml_load_file("users.xml") as $field) {
$this->map[(string)$field->name] = $field;
}
}
public function save($user) {
$rs = $this->conn->execute(
self::INSERT_SQL
,array(
$user->getTitle()
,$user->getName()));

if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
$user->setId($inserted->getId());
}
else {
throw new Exception("Error: ".$this->conn->errorMsg());
}
}
public function findById($id) {
$row = $this->conn->getRow("select * from users where id = ?"
,array((int)$id)
);
if ($row) {
return $this->createUserFromRow($row);
}
else {
return false;
}
}
protected function createUserFromRow($row) {
$user = new User($this);
foreach($this->map as $field) {
$setproperties = (string)$field->presentor;
$value = $row[(string)$field->name];
if ($setproperties && $value) {
call_user_func(array($user, $setproperties), $value);
}
}
return $user;
}
public function add($title, $name) {
$user = new User;
$user->setTitle($title);
$user->setName($name);
$this->save($user);
return $user;
}
protected function insert($user) {
$rs = $this->conn->execute(
self::INSERT_SQL
,array(
$user->getTitle()
,$user->getName()));
if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
if (method_exists($inserted,"setId")) {
$user->setId($inserted->getId());
}
}
else {
throw new Exception("DB Error: ".$this->conn->errorMsg());
}
}
public function save($user) {
if ($user->getId()) {
$this->update($user);
}
else {
$this->insert($user);
}
}
protected function update($user) {
$binds = array();
foreach(array("title","name","id") as $fieldname) {
$field = $this->map[$fieldname];
$getproperties = (string)$field->access;
$binds[] = $user->$getproperties();
}
$this->conn->execute(
self::UPDATE_SQL
,$binds);
}
public function delete($user) {
$this->conn->execute(
"delete from users where id = ?"
,array((int)$user->getId()));
}
}
?>

So, in this way using Data Mapper Pattern, we can map php objects to database in a simple way.

20 September, 2010

Collapsible Menu using jQuery

Displaying all information at once to a user is not a good idea. Instead data can
be presented to user as chunks, if it can be said. A good example of displaying
only some data at a time collapsible list. In the following section, i am building
a show/hide list, a collapsible list using jquery.

We will be implementing a list items that contain child lists, and at the beginning
the child lists are hidden, and can be collapsible.

In following html, we can see that List Item 3 has content; so its child list elements
are hidden and mouse cursor changes to hand when hovered. I will explain each section
and then provide a complete working javascript code for collapsible list using jquery.

Select all the LI list items that have list children elements and add click event
handler. The click event handler checks if the target elment of event matches this.

$("li:has(ul)").click(function(event) {
....

When a parent list item in clicked the we check that if its children are hidden by
using jquery is() function.

if ($(this).children().is(':hidden')) {
.....

If the children are hidden, then we show them using show() function, and if they are
already shown we make them hidden by using hide() function. So this makes the list
collapsible. Return false is done to avoid needless propagation.

$(this).children().show();
.....
$(this).children().hide();
...
return false;

Then we change the cursor to pointer and add a click handler to our outermost list
item.

.css('cursor', 'pointer')
.click();
......

The last line makes sure that cursor for those li list items that do not have ul lists
will be default and no image will be added to those lists.

$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});

So this completes our collapsible list using jquery. Furthermore, more css styles
can be added and more jquery features to make it look better.
Following section has complete code for implementation of collapsible menu in jquery.

//head tag start
//include jquery.js script
//script tag start
$(document).ready(function() {
$('li:has(ul)').click(function(event) {
if(this == event.target) {
if($(this).children().is(':hidden')) {
$(this).children().show();
}
else {
$(this).children().hide();
}
}
return false;
})
.css('cursor', 'pointer')
.click();
$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});
});
//script tag end
//head tag close


  • Item 1

  • Item 2


  • Item 3

    • Item 3.1


    • Item 3.2

      • Item 3.2.1

      • Item 3.2.2

      • Item 3.2.3



    • Item 3.3





19 September, 2010

JSON Basics

JSON is just Javascript. It is a wat to represent objects in Javascript. Using JSON does not involve working with Document Object Model (DOM). Below is a simple JSON format:
var jsnData = { "totals": [
{"location" : "First", "itemsSold" : 10, "bought": 40},
{location": "Second", "itemsSold" : 120, "bought" : 60},
{"location" : "Third", "itemsSold" : 20, "bought" : 40}
]};
Now the above JSON data can be accessed as follows:
//Get total items sold for first location
var firstItemsSold = jsnData.totals[0].itemsSold,
Similarly,
var secondItemsSold = jsnData.totals[1].itemsSold;
var secondItemsSold = jsnData.totals[1].bought;

Accessing the json based server response as json format
//lets consider basic example
//code for xmlhttprequest
if(xhr.status == 200) {
var jsnData = eval( '(' + xhr.responseText + ')' );
alert(jsnData.totals[0].itemsSold);
}
JSON is a better way to send objects or arrays to a server. And for working with such data, server should use some JSON library.

PHP Comet basics

Despite improving the user experience, Ajax still uses the HTTP model, i.e. client sending request for some resource to server and server responding to this request from client. This is generally called "Pull" method/architecture.
However, Comet, the stuff this article is on, uses "Push" architecture. Lets consider ana analogy: in case of chat systems, server pushes data to client as and when necessary at some intervals, as a result of which, communication between the two (client/server) is fast. If, chat systems would have been built using "Pull" method, then the communication would suffer.
Comet pushes information to the client via HTTP streaming. Simply saying, HTTP streaming is a continuous connection with the server that pushes data out to client at certain intervals.
Lets consider some sample code:

//get time the file was modified on
$changed = filemtime("some_file.txt");
$lastChanged = $changed;

//clear the file stats; so that file operation results are cleared
clearstatcache();

//check if it has changed; runs infinitely just for a test; remove this in
//real cases
while(true) {

//sleep for 3 secs; can be set as appropriate to create a delay
sleep(3);

//check the file modified time
$lastChanged = filemtime("some_file.txt");

//clear the file stats; so that file operation results are cleared
clearstatcache();

//check the times
if($changed != $lastChanged) {
$outData = date("d:i:s", $lastChanged);
?>

//send the data across HTTP stream
ob_flush();
flush();
$changed = $lastChanged;
sleep(3);
}
}
?>

Since Comet focuses more on traditional web application servers, it is preferrable to use a system specially designed for HTTP streaming.

Get age from birthdate using php the easiest way

Once i had a situation to get age of a user from his/her birthdate. After some testing, i managed to work it out. Following
code is used to get age from date. I hope this might help someone like me.

//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "08/14/1972";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[1], $birthDate[0], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2] - 1));
echo "Age is:".$age;
?>

Get current page from Codeigniter pagination

Once i had a simple problem to get current page number from codeigniter pagination. After some checks, i managed to get it working by simple one line of code. I hope this will help someone like me.

//here: $this->uri->segment(n) is the segment value that you pass when initializing pagination
//and $config['per_page'] is number of pages to be displayed during pagination initialization in codeigniter
$currentPage = floor(($this->uri->segment(n)/$config['per_page']) + 1);
echo "Current Page:".$currentPage;

16 September, 2010

Search Flickr by username using REST

Searching flickr users by username can be done simply using REST services provided by flickr. Following is a beginning but complete
code that search for a username in flick using REST service of flickr.


//REST url for flickr
$url = "http://api.flickr.com/services/rest";
$data = array(
"username" => "sudhi",
"method" => "flickr.people.findByUsername",
"api_key" => "ur_api_key_here"
);
//this is the query string initialization
$q = http_build_query($data);
$finalUrl = $url."?".$q;
//initialize curl
$ch = curl_init($finalUrl);
//return the response as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the curl
$result = curl_exec($ch);
//use simpleXml for parsing the xml response
$xmlStr = simplexml_load_string($result);
foreach($xmlStr->user as $people) {
$attrs = $user->attributes();
//ths $attrs contains user information
echo "
";
print_r($attrs);
echo "
";
}

Create breadcrumb from array

Creating breadcrumbs can sometimes be really dificult. Breadcrumbs can be created from array in php using some simple code.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.


$id = $_GET['id'];
if ( strlen( $id ) < 1 ) $id = "home";
//this array contains page lists, with id, title and parent page named as main in here
$pages = array(
'home' => array( 'id'=>"home", 'main'=>"my_home", 'title'=>"Home",
'url'=>"bcrumb.php?id=home" ),
'members' => array( 'id'=>"users", 'main'=>"home", 'title'=>"Members",
'url'=>"bcrumb.php?id=members" ),
'sudhir' => array( 'id'=>"jack", 'main'=>"users", 'title'=>"Sudhir",
'url'=>"bcrumb.php?id=sudhir" )
);
//function to create breadcrumb from array
function crumbs( $id, $pages ) {
$bCrumbList = array();
$pageid = $id;
while(strlen($pageid) > 0) {
$bCrumbList[] = $pageid;
$pageid = $pages[ $pageid ]['main'];
}
for($i = count( $bCrumbList ) - 1; $i >= 0; $i-- ) {
$page = $pages[$bCrumbList[$i]];
if ($i > 0) {
echo( " echo( $page['url'] );
echo( "\">" );
}
echo( $page['title'] );
if ( $i > 0 ) {
echo( "
| " );
}
}
}
echo "Crumbs:" .crumbs($id, $pages);
echo "
";
echo "Page:".$id;


Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.

08 September, 2010

Get only the path for a file

Sometimes it is required the get only the path that a file exists. In such cases following function could be of some help. I
hope this function helps someone like me

function getPath($path) {
if(substr($path, -1, 1) == '/') {
return $path;
}
else {
$pathArr = explode('/', $path);
$total = count($pathArr);
$end = $pathArr[$total - 1];
if(substr_count($end, '.') > 0) {
array_pop($pathArr);
}
$finalPath = implode('/', $pathArr);
return $finalPath;
}
}
?>

Load all class at once in php

Loading all the classes at once in php can be done by a simple code. If we have requirement to load lots of php classes
at once then this can be really boring. So in order to load all class at once in php we could write some code. Following
php code does the job.

function loadModules($dir) {
//create an array to hold the class names
$classes = array();
//usign DirectoryIterator class of php to get the handle of directory that contains the classes
$dh = new DirectoryIterator($dir);
//loop through each file
foreach($dh as $file) {
//check if the file is not a directory and ends with a .php extension
if($file->isDir() == 0 && preg_match("/[.]php$/", $file)) {
//include the class
include_once($dir."/".$file);
$class = preg_replace("/[.]php$/","", $file);
$classes []= $class;
}
}
return $classes;
}
?>

05 September, 2010

Integrating Videowhisper in CodeIgniter

Some times ago, i confronted a problem of integrating videowhisper with CodeIgniter. Searched through videowhisper forums but could not get exact solution, though i managed to do it using info regarding integration for plain php code.
I hope this might help someone like me.
Lets say we have a project folder named "test"
Step 1:
Add the "videowhisper_conference.swf" file in you root folder (project folder test) and its necessary folders like "uploads", "emoticons", etc. in the same folder

Step 2:
Copy the contents of "videowhisper_conference.php" into your view file, where you want to display the video.

Step 3:
Create function in your controller for each of the file, such as videologin for vc_login.php, videostatus for vc_status.php file. Do this for all the .php files that you require.

Step 4:
Add following code in you .htaccess file
RewriteCond %{QUERY_STRING} room_name(.*)

RewriteRule vc_login.php(.*) folder_name/controller_name/videologin/%1? [L]
RewriteRule vw_rooms.php(.*) folder_name/controller_name/videorooms/%1? [L]
RewriteRule vw_files.php(.*) folder_name/controller_name/videofiles/%1? [L]
RewriteRule vc_status.php(.*) folder_name/controller_name/videostatus/%1? [L]
and so on for all the files that you need.

You are done.
I've mentioned general steps in this case. You need to pass on the logged in user id and other required values accordingly.
Hope it helps.