by
faheem on May 15th, 2010
It has been long since written on my blog, how lazy I m, why not get some treatment form the people around me. Why not developers all around chop ma head and screw me up for being so lazy. But mind you don’t try this, coz I belong to the area where people are treated so hard that nobody can even think of. Now don’t ask me where do I belong to.
Its Saturday, off, but I m on and m in great mode. I don’t know why m I feelen so happy though we lost our semi last night. I’m juz chilling.
Gaad daym, what I am written on my technical blog, it shon’t be like this. So lemme move to the topic and put aside this mess and hassles.
Since yesterday I’m try to get this work for me, I’s unable yesterday, but today it really worked for me. Nothing else but COM did the job for me. I m going to share this code with you and m sure that it will serve you lot. Don’t tell anyone that I found this code on the web otherwise I will punch you down and kick you skinny ass.
The code here will read contents form .doc, save those to .txt file and then read contents from that txt file. Here is the code.
$word = new COM("word.application") or die("Unable to instantiate Word");
$word->Documents->Open($file);
$new_filename = substr($file,0,-4) . ".txt";
// the '2' parameter specifies saving in txt format
$word->Documents[1]->SaveAs($new_filename,2);
$word->Documents[1]->Close(false);
$word->Quit();
//$word->Release();
$word = NULL;
unset($word);
$fh = fopen($new_filename, 'r');
// this is where we exit Hell
$res = fread($fh, filesize($new_filename));
fclose($fh);
unlink($new_filename);
echo $res;
So what we’re doing here.
Instantiate COM, open file, save content as .txt file, open .text file and get contents. That’s it.
Juz give it a try and you will find it quite helpful.
by
faheem on September 17th, 2009
I worked on enterprise level application for one year using Eclipse, Php Designer, and Dreamweaver. We were using Eclipse for checking in and out (updating and committing)
When I joined the team, configuration was already in place in the Eclipse, so I never intend to make configuration. Whenever configuration needed, Team lead was up to the task and was responsible for the entire configuration. I came across new terms like SVN, Commit, and Update for the first time as I was using cute ftp for uploading and downloading files from server before.
Here our job was to write code, complete tasks and commit them using our team lead system. First job in the morning was to update the change as some developers were making change to our project in United States. Our team lead system went of order few times during this period, but we were always looking toward him for the configuration. I remember that once he configured everything on my system, but I never intended to look how everything are done.
Today I found myself stuck in the middle. As I’m going to start working on new project, I tried to do the entire configuration myself.
Believe I was having no clue how to do it. Thanks to some nice soul out there on the internet who have posted the entire step by step procedure. I am going to write those steps for you.
Import project in Eclipse
1. File >> New >> Project >> SVN >> Checkout projects from SVN
2. Next
3. Create a new repository location
4. Next
5. Enter URL as
http://yourserver.com/alpa_proj
6. Next
7. Select the directory
8. Next
9. Choose: checkout as project configured using the New Project Wizard
10. Finish
by
faheem on August 27th, 2009
Note: This article was written in 2008, when I was working in small firm. Publishing it again here for newbies.
After working for about one year in website development industry of Pakistan I’ve realized a very serious issue. This may be happening in other countries as well, as I haven’t had worked with international organization, especially professionals.
The problem is mixing presentational logic with business logic. In simple words I would say maxing HTML with server scripting language like php, asp, coldfusion etc.
Here I would appreciate Microsoft professionals who have done tremendous job by developing Asp.net language. The way they have separated asp.net and html code from C# and VB.NET code is fabulous. However I would like to mention that in the beginning-in early versions of ASP.NET-the problem was there. However with the passage of time and introducing newer and more mature versions like ASP.NET 2.0 they have addressed lots of issues.
Before going into the details of problem mentioned above I would also like to comment about some companies who are providing open source solutions for languages like PHP etc. The contribution made by oscommerce (having the above drawback), zencart(I haven’t studied but heard that it is a bit mature shopping cart solution than oscommerce) and joomla(very nice and more mature content management system) to php cannot be ignored.
The most important contribution is made by those who have developed frameworks(MVC’s) like Zend, Symfony, cakePhp, mojave(lacking documentation and community support) etc. One cannot imagine how worthy and brilliant job they have done and how easier they have made work for lazy professionals like me.
Two months back I was introduced to mojavi by our company senior web developer. In the first few days I was exhausted and bored. However after developing a simple login application in mojavi I found it quite helpful. But things didn’t move forward coz of lacking documentation and community support.
I stopped working in mojavi but the virus of working in frameworks sneak in my heart and I started googling different frameworks.
Next few days I studied cakePhp, symfony and then zend, red their documentation, browse their community support sites and forums and also red articles about their differences.
Finally and luckily I selected Zend framework-This was because of small configuration overhead of zend framework than other frameworks.
After working in zend MVC I realized how easier it is to make a web application and how easy it is to extend and maintain existing one.
Now let me discuss the real problem which has made me sick since last few days.
After joining new organization 6 days back I was assigned a project for modification. The project was constructed in oscommerce. Boss was expecting that I would finish some small modification in few hours but I trapped in the middle and was unable to browser where modification needs to be made.
When boss arrived and asked me about the modification I was having no idea what to say and I felt a bit shy at that time. After telling him that I haven’t completed the modification he was a bit shocked and worried because he might be thinking that I was not a right person for the post I had been hired. He took me to his office and asked me about projects I had previously worked on. After showing him my projects he got satisfied but still I could see uncertainty in his eyes.
Why all this happened and why I trapped in the middle will I think clear the problem I have mentioned in the beginning..
As I have already mentioned that project was constructed in oscommerce so those how know or have worked in oscommerce will better understand the way oscommerce has been developed. Although they have separated php code form html up to some extent, however it is not as mature as joomla content management system or model view controller frameworks.
Well, oscommerce was not a big obstacle. The more irritating thing was the way previous programmer had implemented and constructed the pages. After working in office for about 10 hours I managed to complete some modifications but not entire.
When I came home, installed oscommerce and started doing the same modifications it took me minutes to complete them.
So I took some deep breathes and started thinking about whom to be blamed. But after thinking for about two hours I realized that no one could be blamed because client needs their projects soon, so developers only think about the construction not about what will happen in future if he himself or someone else try to extend or modify the project.
Lot of website have been made in similar scenarios and situations.
So as a professional one needs to be very careful while modifying the project.
Although professional developed application based on the client recommendations however I think we professional should think seriously about the future extensions and maintenance and try to make application both client and professional friendly.
by
faheem on July 14th, 2009
In my previous article I discussed some of the nice thing of object oriented programming. Inheritance –creating sub classes from inheriting parent, contain all the attributes of the parent class plus its own. Polymorphism means different form, like overloading and overriding methods and dynamic binding- deciding which class in the inheritance tree should be called on runtime, are techniques that give great benefits to programmers.
In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class, refer to the same class.
Consider the following example.
class Person {
protected $_name;
protected $_age;
protected $_gender;
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setAge ($age) {
$this->_name = $age;
}
public function getAge() {
return $this->_age;
}
public function setGender($gender) {
$this->_gender = $gender;
}
public function getGender() {
return $this->_gender;
}
}
In object oriented programming it’s always a good practice to define getter and setters. In php you can define __set and __get as setters and getter.
To create an object of the above class and define person properties, we will need to write the following code.
$person = new Person();
$person->setName(“person_name”);
$person->setAge(24);
$person->setGender(“male”);
And now If you want to get these values, write
$person->getName();
$person->getAge();
$person->getGender();
Well, if you want to set values using a single statement, you will need a code similar to this.
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);
To achieve this, you will need to write the following statement in all your setters
public function setName($name) {
$this->_name = $name;
return $this;
}
The only thing we need here is “return $this”. This statement return a reference to the same object.
Place this statement in your setAge() and setGender(), and now you can write
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);
for setting all the three properties.
suggestion, if any, is welcome. Cheers
by
faheem on July 14th, 2009
Object oriented programming concepts were introduced in PHP1.4, I guess.
How many people around you play with object oriented programming?
If not working in any kind of MVC frameworks, I guess very short number of people.
Developers are often used to structured programming and don’t bother themselves learning object oriented programming concepts and paradigm.
Well, when software engineers realized that it’d become very difficult to manage and maintain thousand lines of code as well as impossible to represent real world object in computer world, object oriented programming was introduced. Since then dramatic improvements have been made to OOP.
In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great value, usage and advantages, however class and objects are the most basic concept.
Class is blue print containing properties and method associated with same entity. Object is the instance of the class and is used to access properties and method of the class.
In addition to OOP, design pattern make jobs easier for the programmers.
Singleton, factory and specially MVC design patterns are very useful these days.
In singleton design pattern one object of the class exist throughout the life cycle of the software application. If programmer tries to instantiate another object of the same class, a reference to the object instantiated earlier, is granted.
A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.
In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.
Revolution of MVC design patterns cause dramatic changes in software development life cycle. Prior to MVC, developers were mixing code all around. It was difficult to figure out where the business code resides and where presentation code is written. Intelligent software engineers, though, were trying hard to separate their business logic from presentation logic; this however wasn’t effective enough for new comers to understand their code and to do necessary maintenance. Without the help of the person behind the project, it’d taken more time to understand the directory structure used.
These draw backs were mostly addressed when MVC design patterns were introduced.
In MVC design pattern M stands for Model. Model contains your application’s business logic.
V stands for View. It’s the presentation layer.
While C stands for controller that work as glue between view and model. From glue I mean it takes data from view and give it to the model, model then process the data and produced desired results. The data, thus obtained, is given to the view. Controller can also be compared to event handlers. It responds to certain events such as posting the data back to server by clicking submitted data.
Hopefully I will unveil some other fact about OOP and design pattern later some time.
by
faheem on July 13th, 2009
While working with AJAX, you will need to get data after sending request to the server. You can use three ways to get the data form the server.
1. In xml Format
2. HTML Format
3. Json Format
Though xml has several advantages, however processing data at the client will put extra burden.
HTML, can easily be handle, is however more resource or you can say bandwidth extensive.
So JSON fall in the middle of both.
PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.
Let’s first look at the server side.
For example we have the following array.
$data = array(
'items'=>array(
'firstname'=>'faheem',
'lastname'=>'abbas',
'address'=>'pakistan'
)
);
To create JSON response, simply write
echo json_encode($data);
This will give the following result
{"items":{"firstname":"faheem","lastname":"abbas","address":"pakistan"}}
Now at the client side to send AJAX request, you will need to create the following code.
Keep in mind that we are using prototype for making AJAX request.
That’s it.
by
faheem on July 2nd, 2009
Session data by default is stored in /tmp directory on the server in the form of text files. It wouldn’t be a good practice to store session information in the default directory because users can easily get these information. You must either change the directory, or the best practice is to store the information the database. Storing session data in the database not only increase your application security, but also provide you an ability to fetch session related information easily from the database.
PHP provide very easy mechanism and functions for storing session information in the database.
In order to store information in the database you will need to have a table containing fields such sessionId for storing unique session Id, sessionData for storing session data and accessDate that store date when session was last accessed.
Once table is successfully created, saving session requires only two steps.
1. Creating function that interact with and store data in the database.
2. Tell PHP to use the functions defined by using session_set_atuo_save() method.
Now let’s discuss these two steps
1. Creating functions for interacting with database
Before using session_set_auto_save() method, we will need to define six method. These method will then be passed as argument to the session_set_auto_save() method. These six methods are each called on the even taken place. Events are fired when session is started, session is closed, session data is read, session data is written, session data is destroyed, and the six argument/function is used for garbage collection. Garbage collection is used to free resources etc.
Now let’s define and discuss functions for each of these events.
(i) Defining a function which will be called when session is started.
$dbConn = null;
function open_session()
{
global $dbConn;
$dbConn = mysqli_connect('host','username','password','dbname') or die('cannot connect to the database');
}
This method is called each time session is started. The function contains code for connecting to the database only. You can place whatever you wish.
(ii) Defining function called when session is closed
function close_session()
{
global $dbConn;
$dbConn = mysqli_close();
}
(iii) Defining function called when session is read
function read_session($sid)
{
global $dbConn;
$q = sprintf('SELECT data FROM sessions WHERE id="%s"', mysqli_real_escape_string($dbConn, $sid));
$r = mysqli_query($dbConn, $q);
if (mysqli_num_rows($r) == 1) {
list($data) = mysqli_fetch_array($r, MYSQLI_NUM);
return $data;
} else {
return '';
}
}
This function take current sessionId as argument and read the data from the database.
(iv) Defining function called when session data is written
function write_session($sid, $data)
{
global $dbConn;
$q = sprintf('REPLACE INTO sessions (id, data) VALUES ("%s", "%s")',
mysqli_real_escape_string($dbConn, $sid), mysqli_real_escape_string($dbConn,
$data));
$r = mysqli_query($dbConn, $q);
return mysqli_affected_rows($dbConn);
}
This function takes two argument sessions current Id and the data to be written. The code written here inserts session id and data into the database table and return number of affected rows.
(v) Defining function, called when session is destroyed
function destroy_session($sid)
{
global $dbConn;
$q = sprintf('DELETE FROM sessions WHERE id="%s"',
mysqli_real_escape_string($dbConn, $sid));
$r = mysqli_query($dbConn, $q);
$_SESSION = array();
return mysqli_affected_rows($dbConn);
}
This function take single argument sessionId and delete the row based on this id.
(vi) Defining function that is called when resource need to be freed.
function clean_session($expire)
{
global $dbConn;
$q = sprintf('DELETE FROM sessions WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()',
(int)$expire);
$r = mysqli_query($dbConn, $q);
return mysqli_affected_rows($dbConn);
}
This function is used to delete session data from the database based on the $expire argument it accepts.
Now as we have defined all the required function, its time to call session_set_auto_save() method.
Before starting the session you would need to call session_set_auto_save() method as
session_set_auto_save('open_session','close_session','read_session','write_session','destroy_session','clean_session');
session_start();
…….
by
faheem on June 30th, 2009
Today highly confidential data such as credit card number, social security number etc are stored and handle through web. So it must be your primary goal to make your web application secure enough, so that users/visitor feels confident enough while using your application.
Here in this article I am going to give you some tips that are worthy to be remembered and taken care of in application development process.
1. You may have heard about register_globals. They make PHP variables usage easy. However they have certain disadvantages such as users can easily sneak into your application by easily passing data through $_POST, $_GET or $_COOKIE etc. So you shouldn’t rely on register_global. Disable them would be nice decision.
2. Most of the time we use variable directly, without first initializing them. For example
if (condition) {
$flag = TRUE;
}
If you don’t initialize $flag to false, user can easily set it to true using, $_POST, $_GET or $_COOKIE.
1. Verify all incoming data before processing. Verification highly depends on the type of data. If you need to insert integer data in the database, make sure that proper data is submitted through form.
2. Be very much careful when using function that run commands on the server. These function include exec(), passthru() and backticks (“) etc.
3. You must change the directory where session data is stored by default. Another good approach would be to use database to store session information.
4. When uploading file to the server, it would be good practice to rename the file(s) before storing them. Name must be safe and not guessable.
5. Don’t reveal error on live site. Errors reveal very important information, so they must be taken care of.
6. Take care of SQL injection. If user provides malicious information, your SQL query shouldn’t break.