Narendra Dhami

My Site

Archive for the ‘PHP’ Category

Optimizing PHP

Posted by Narendra Dhami on September 8, 2009


A HOWTO on Optimizing PHP

PHP is a very fast programming language, but there is more to optimizing PHP than just speed of code execution.

In this chapter, we explain why optimizing PHP involves many factors which are not code related, and why tuning PHP requires an understanding of how PHP performs in relation to all the other subsystems on your server, and then identifying bottlenecks caused by these subsystems and fixing them. We also cover how to tune and optimize your PHP scripts so they run even faster.

Achieving High Performance

When we talk about good performance, we are not talking about how fast your PHP scripts will run. Performance is a set of tradeoffs between scalability and speed. Scripts tuned to use fewer resources might be slower than scripts that perform caching, but more copies of the same script can be run at one time on a web server.

In the example below, A.php is a sprinter that can run fast, and B.php is a marathon runner than can jog forever at the nearly the same speed. For light loads, A.php is substantially faster, but as the web traffic increases, the performance of B.php only drops a little bit while A.php just runs out of steam.
More …

Advertisements

Posted in PHP | Leave a Comment »

Create daemons in PHP

Posted by Narendra Dhami on September 3, 2009


Everyone knows PHP can be used to create websites. But it can also be used to create desktop applications and commandline tools. And now with a class called System_Daemon, you can even create daemons using nothing but PHP. And did I mention it was easy?
What is a Daemon?

A daemon is a Linux program that run in the background, just like a ‘Service’ on Windows. It can perform all sorts of tasks that do not require direct user input. Apache is a daemon, so is MySQL. All you ever hear from them is found in somewhere in /var/log, yet they silently power over 40% of the Internet.

You reading this page, would not have been possible without them. So clearly: a daemon is a powerful thing, and can be bend to do a lot of different tasks.
Why PHP?

Most daemons are written in C. It’s fast & robust. But if you are in a LAMP oriented company like me, and you need to create a lot of software in PHP anyway, it makes sense:

* Reuse & connect existing code
Think of database connections, classes that create customers from your CRM, etc.
* Deliver new applications very fast
PHP has a lot of build in functions that speed up development greatly.
* Everyone knows PHP (right?)
If you work in a small company: chances are there are more PHP programmers than there are C programmers. What if your C guy abandons ship?

Possible use cases

* Website optimization
If you’re running a (large) website, jobs that do heavy lifting should be taken away from the user interface and scheduled to run on the machine separately.
* Log parser
Continually scan logfiles and import critical messages in your database.
* SMS daemon
Read a database queue, and let your little daemon interface with your SMS provider. If it fails, it can easily try again later!
* Video converter (think Youtube)
Scan a queue/directory for incoming video uploads. Make some system calls to ffmpeg to finally store them as Flash video files. Surely you don’t want to convert video files right after the upload, blocking the user interface that long? No: the daemon will send the uploader a mail when the conversion is done, and proceed with the next scheduled upload

Deamons vs Cronjobs

Some people use cronjobs for the same Possible use cases. Crontab is fine but it only allows you to run a PHP file every minute or so.

* What if the previous run hasn’t finished yet? Overlap can seriously damage your data & cause siginificant load on your machines.
* What if you can’t afford to wait a minute for the cronjob to run? Maybe you need to trigger a process the moment a record is inserted?
* What if you want to keep track of multiple ‘runs’ and store data in memory.
* What if you need to keep your application listening (on a socket for example)

Cronjobs are a bit rude for this, they may spin out of control and don’t provide a framework for logging, etc. Creating a daemon would offer more elegance & possibilities. Let’s just say: there are very good reasons why a Linux OS isn’t composed entirely of Cronjobs 🙂
How it works internally

(Nerd alert!) When a daemon program is started, it fires up a second child process, detaches it, and then the parent process dies. This is called forking. Because the parent process dies, it will give the console back and it will look like nothing has happened. But wait: the child process is still running. Even if you close your terminal, the child continues to run in memory, until it either stops, crashes or is killed.

In PHP: forking can be achieved by using the Process Control Extensions. Getting a good grip on it, may take some studying though. More …

Posted in PHP | Leave a Comment »

Simple Process for PHP Projects

Posted by Narendra Dhami on September 3, 2009


PHP_Process

More …

Posted in PHP | Leave a Comment »

Solutions To Session Attacks

Posted by Narendra Dhami on September 2, 2009


Recently i wrote two other security article on XSS and SQL Injection. I find many interesting facts and solutions on those topic that i research about and wanted to know more about other security measure. Thus, in this article i will discuss on different type of session attacks and how we can better protect ourselves against these attacks to better secure our web portal.

Session attack is nothing more than session hijacking. The most important information in session attack is to obtain a valid valid session identifier (SID). There are three common methods used to obtain a valid session identifier.

* Session Prediction
* Session Capture
* Session Fixation

More …

Posted in PHP, Web | Leave a Comment »

Automatic Face Detection in Photos with PHP

Posted by Narendra Dhami on August 20, 2009


Face Detection in Photos with PHP

I have always wondered how to detect faces automatically with php script. I have seen in many photo sharing and social network sites automatically detect a face and tag a name after being uploaded.

In this article, i will explain how possible this task can be achieved with simplicity with OpenCV and PHP Facedetect extension. Both are free to download and opensource.

Goal

To auto detect faces in a photo and draw pink box around the faces with a php script running a linux centos server. Please note that face detection and face recognition are two different things. To recognize a face you have to first detect a face and then do the required processing.

Requirements

– Linux server running Centos with SSH access

– PHP/Apache
– GD Library
– OpenCV [Download]
– PHP Facedetect extension [Download]

PHP facedetect extension is very simple. All you have to do is call a function face_detect(p) and it will give all the x,y coordinates in a photo where we draw a square. face_count() will output how many total faces in the given photo. For documentation see here

Installation

We install opencv and then we compile the php facedetect extension with php.

How to Install OpenCV

If you are running centos then one single line will install opencv.

yum install opencv

OpenCV may also need the following depencies to work properly and you will need to install them as well.

yum install ibpng libpng-dev zlib libjpeg libjpeg-dev libtiff libjasper swig python pkgconfig gtk gtk-dev

For more installation instructions on linux see here

The opencv will be installed in /usr/local/share/opencv and all the important facedetection training files known as “haar training” can be found in haarcascades folder in xml format (like haarcascade_frontalface_alt.xml)

How to test run OpenCV

Inorder to test run opencv you have to compile the samples folder. Go to /usr/local/share/opencv/samples/c/

Run this command to compile to binary.

./build_all.sh

If you find large number of errors and variables not declared like shown below..

Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc’
to the PKG_CONFIG_PATH environment variable
No package ‘opencv’ found
….

run

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
./build_all.sh

and then it will compile.

To test run the opencv run the following command in the c folder for a test.jpg photo.

./facedetect --cascade="../haarcascades/haarcascade_frontalface_alt.xml" test.jpg

Since your server does not have Xwindow installed, you probably do not see the output just the processing time.

If you see error “error while loading shared libraries: libcxcore.so.2: cannot open shared object file: No such file or directory” then see this solution

Install PHP Facedetect Extension

Installing the PHP facedetect extension is very easy. Just download the package and compile it for PHP.

wget
tar zxf facedetect-1.0.0

then

phpize && configure && make && make install

If you see phpize command not found error, install php developer libraries

yum install php-devel
OR
yum install php5-devel

then

open php.ini and make sure you add this line.

extension=facedetect.so

If facedetect has been successful, you will see this enabled in test.php.

facedet.PNG

Thats it! all the installation part is over!

Writing a PHP Script

Before you start writing php script make sure you copy all xml files in /usr/local/share/opencv/haarcascades folder to the web folder.

and this simple two lines to from php to call the function


<?php
//face_count() outputs total faces detected
// face_detect() outputs assoc array of x,y,width,height of each face recognized

$total= face_count('test.jpg','haarcascade_frontalface_alt.xml');
$coord= face_detect('test.jpg','haarcascade_frontalface_alt.xml');
print_r($coord);
?>

Make sure the path of xml files are correct else you would see a blank face or bool(false) output. Once you get this co-ordinates all we have to do is use php gd library to draw square around the face with the above coordinates.

This script will do that and you have call the script with photo file like this http://domain/face.php?file=test.jpg and the test.jpg file should be in the same folder


<?php
//face.php -> detects faces and draws a pink square on faces

function LoadJpeg($imgname)
{
    $im = @imagecreatefromjpeg($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

$total= face_count($_GET['file'],'haarcascade_frontalface_alt.xml');
$ord= face_detect($_GET['file'],'haarcascade_frontalface_alt.xml');

$im = LoadJpeg($_GET['file']);
$pink = imagecolorallocate($im, 255, 105, 180);

if(count($ord) > 0) {

foreach ($ord as $arr) {
imagerectangle($im,$arr['x'] ,$arr['y'] , $arr['x']+$arr['w'],
$arr['y']+$arr['h'], $pink);
}

}
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>

Just remember haarcascade_frontalface_alt.xml are haar training files used for face detection. You can play around with other training files like to detect various body parts, not just faces.

haarcascade_frontalface_alt.xml
haarcascade_frontalface_alt_tree.xml
haarcascade_fullbody.xml
haarcascade_profileface.xml
haarcascade_lowerbody.xml
haarcascade_upperbody.xml

Other Useful Links

Facedetection with pure PHP without OpenCV [visit site]
Facedetection with javascript [visit site]

OpenCV Face Detection Page [visit site]

Enjoy!

Original From http://corpocrat.com/2009/08/18/automatic-face-detection-with-php-in-linux/

Posted in PHP | Leave a Comment »

Really Useful Classes And Libraries For PHP Developers

Posted by Narendra Dhami on August 18, 2009


Today millions of websites and servers across the Internet are powered by PHP. Originally created by Rasmus Lerdorf in 1995 so that anyone can easily create a Personal Home Page; PHP has come a long way and is now widely used as general purpose scripting language that is suitable for majority of web development projects.

Numerous PHP Frameworks have evolved to enable rapid web development with PHP. However even greater number of standalone PHP libraries and classes are available which provide similar benefits. W3Avenue has compiled a list of some really useful classes and libraries that every PHP developers should be familiar with. Whether you like to use a PHP Framework or prefer to work without one, your productivity can multiply with the help of these libraries and classes. More …

Posted in PHP | Leave a Comment »

20 Interesting facts about PHP: A PHP developer should know

Posted by Narendra Dhami on August 11, 2009


Are you a PHP developer? Do you know all about PHP along with all these facts that I am presenting to you below? I bet you you don’t know at least 10 out of 20. You don’t believe me, lets read all 20 points below and find out how many of them you know already?

As a PHP developer you should know all these facts. I call them interesting because, almost all points surprised me. Though I am a PHP developer from the past 4 years but didn’t know all these facts.

1. PHP originally stood for Personal Home Page.
2. PHP which is now officially known as ‘Hypertext Preprocessor’ was released in the year 1995.
3. Initially written as a set of Common Gateway Interface (CGI) in ‘C’ (1994).
4. PHP was originally designed to replace a set of Perl scripts to maintain his Personal Home Pages (also known as PHP).
5. PHP was originally created by Rasmus Lerdorf in 1995. He wrote the original Common Gateway Interface (CGI) binaries.
6. Zeev Suraski and Andi Gutmans, two developers at the Technion IIT, rewrote the parser in 1997 and formed the base of PHP 3.
7. PHP 3 was official launched in June 1998.
8. Suraski and Gutmans rewrote the PHP 3’s core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel.
9. On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released.
10. The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.
11. On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 introduced full featured object-oriented programming support. It was there in PHP 3 and PHP 4 but only the basic features.
12. PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) due to restrictions on the use of the term PHP.
13. PHP was originally designed to create dynamic and more interactive web pages. It is the most widely-used, open-source and general-purpose scripting language.
14. It is possible to use PHP in almost every operating system. PHP can be used in all major operating systems including Linux, Microsoft Windows, Mac OS X, and RISC OS.
15. PHP uses procedural programming or object oriented programming and also a mixture of them.
16. PHP is installed on over 20 million websites and 1 million web servers.
17. 75% of Web 2.0 sites are built in PHP.
18. There are about 5 million PHP developers worldwide.
19. The latest release of PHP till now is 5.3.0. It was released on Jun 30, 2009. PHP 6 is under development alongside PHP 5. Major changes include the removal of register_globals, magic quotes, and safe mode. The reason for the removals was that register_globals had given way to security holes, and magic quotes had an unpredictable nature, and was best avoided.
20. Some of the biggest online brands, such as Facebook, ProProfs, Digg, Friendster, Flickr, Technorati, and Yahoo! are powered by PHP.

Posted in PHP | 3 Comments »

30 Useful PHP Classes and Components

Posted by Narendra Dhami on August 10, 2009


Simplicity and extensibility are the main reasons why PHP became the favourite dynamic language of the Web. In the last decade, PHP has developed from a niche language for adding dynamic functionality to small websites to a powerful tool making strong inroads into large-scale Web systems.

Below I present 30 useful PHP classes and components that you can use to test, develop, debug and deploy your PHP applications. Let me know if I missed anything or if you have something to add. More …

Posted in PHP | Leave a Comment »

Loads of Essential PHP Tools & Resources For Web Developers

Posted by Narendra Dhami on August 7, 2009


PHP is one of the most popular development languages for building dynamic web applications today. PHP offers many advantages; it is fast, stable, secure, easy to use and open source (free) but it was created by Zend and some critics complain about PHP being influenced by commercial interests and that PHP could be much better if the commercial offerings from Zend where part of the basic PHP platform. In the area of performance and advanced caching this may be true but it seams like open source PHP community gets around the possible shortcomings quite well. Some of the most influential and popular open source CMS/Publishing platforms like WordPress, Joomla and Drupal all rely on PHP and many others do to. Being familiar with PHP and having a good toolbox for working effectively with PHP is essential for most Web Developers because you will run into some PHP code at some point in your career – I guarantee you that!

In this article I have compiled an extensive list of tools and resources that any php developer should be aware of and which will make their life easier. More …

Posted in PHP | Leave a Comment »

Planning your PHP project. The easy way.

Posted by Narendra Dhami on July 7, 2009


This is something that I have personally struggled with since I became a programmer. Proper planning can make or break an application. Without it, a program can become very difficult to manage, update and scale. Your method of organization and inheritance needs to be thought out from the beginning before it is ever implemented in code. I can attest that trying to simply plan a project as you go and write each function as it comes will result in terrible code, poor functionality, higher bandwidth costs and a lack of scalability.

Now I am no project planning expert but maybe this will help out some beginners and get them pointed in the right direction. I am going to break this up into a few different sections and try to keep it as general as possible to cut back on confusion.

Step 1: Brainstorming

Grab a pen and paper (or Notepad) and start brainstorming the different features and sections your application will have. Start off with the main ones. If it is a blog then some major sections might be posting, comments and administration. Once you’re satisfied, take one section at a time and dig a little deeper. The comments section, for example, will need a submission form, spam protection, form validation and error output, etc. Keep refining this data until you are brain-dead. I would even recommend revisiting it every day for a couple days. This will ensure that you have covered all angles.

Step 2: Planning

So now you have a document (or two) outlining the different features and sections of your website. Now this is far from a spec. We need this data to be more organized and easy to read. Enter mind maps. A mind map is sort of like a web diagram that you did in grade school. They can be very difficult to do on paper (be sure you have plenty of eraser). I recommend using a program called FreeMind, which is a great program that allows you to get the process and functionality of your program on paper in a clear and concise manner.

When creating your MindMap, start off with a single node that is your software’s name. Then think of what a user can do from the home page and consult your brainstorming documents. Once you have your first level of functionality mapped out, go into each node one-by-one and input the different elements from your brainstorming documents. Repeat this process until you have everything mapped out. The software makes it very easy to move stuff around later on and has plenty levels of undo so don’t worry about simple mistakes.

Step 3: Functionality

Every advanced programmer has their own method for mapping out functionality (even if they just keep it all in their head). It is a good idea to map out each function separately (or even just the main functions). I personally recommend UML (Unified Modeling Language); there are many programs out there that use UML and provide a great environment to create your models.

Step 4: Database

The database is the backbone of your program. Mapping out a database can be difficult, however, proper database planning can cut back on hours of extra programming and stress. The best program I have found for mapping database architecture is Notepad or FreeMind. Start from your most important table (most likely your user table) and build from there. All tables usually interact with one another eventually. If you’re starting with a user table, write down all the fields, data types, etc that go with it, using your MindMap and UML diagrams as a resource.

Step 5: Execution

Start with your database. This is the foundation of any application. Build it slowly and feel free to revise as you go along (but be sure to update your database diagram). Once you are satisfied and your database is 100% (at least according to your diagram) go ahead and fill in some sample data. You can add data later as you need it.

Using your MindMap and UML diagrams as a guide, start by creating key site functions and classes. If you are creating a blog then you would have a class that handles user data and common user functionality. The same goes for comments, form validation, managing users, etc.. Once you have built as much as you can without the need for a front-end, then you can proceed.

A decent template system is always a good idea, it does take out a lot of the work involved and make it easy for non-technical designers to implement functionality within their designs. Not to mention updating and adding UI later on is much easier.

Using your template system, start to piece together the site in a logical order. It might be a good idea to begin with your administration area but that can really depend on the program and how advanced the administration is. When you get to the front-end, start with your login and session management, then proceed to sign-up, then move onto the users profile.

A good piece of advice I have heard is to code in the order in which a user would use your site or application. I interpret this loosely as this can change drastically depending on what your program calls for.

Originial Source from: http://blog.code-purity.com/archives/2009/7/3/planning_your_php_project_the/

Posted in PHP | Tagged: | Leave a Comment »