Narendra Dhami

My Site

Archive for the ‘PHP’ Category

PHP Certifications. Where, Why And, How To Get Them

Posted by nsdhami on October 21, 2009

Becoming a certified PHP developer, does not mean that you become a better developer but, it can surely give you some more chances to get the job. We tried to do a little research about PHP certifications, where to get one, what it takes to get one and why you need it. We also tried to find some online tests for you in order to prepare yourself before you actually go for it.

Where?

Zend

zendlogoThe industry’s standard can not be anything else than Zend’s Certification. Zend has been running the PHP certification program for more than 4 years and has certified nearly 5000 PHP developers. Actually, there is a contest running at the Zend site that will reward the 5000th certified developer with $5000. This is what they say:

We are rapidly approaching the 5000 PHP Zend Certified Engineer and we would like to give the 5000th person to achieve this prestigious accomplishment a special gift of $5000 in Zend Training Units and if we reach this milestone before ZendCon09 – a free entry pass to the conference!

There are guides and online exams that can help you prepare yourself to get the certification but you have to pay some money to get to them except the Zend Framework Certification study guide that comes free of charge.

There are 2 ways to get the certificate. The first one is by purchasing the examination from the Zend online store and the second one is by scheduling an exam with Pearson Vue, the company with which Zend certifications are executed.

Upon certification, you are listed to the Zend Yellow Pages, where a lot of employers look into for PHP developers and you get special discounts on Zend PHP conferences worldwide.

W3Schools

w3certW3Schools has been a web development resource heaven for many years now. It is not luck that it is the first site to visit for most of people who want to learn web technologies and development. Recently, w3schools has been rolling out a PHP certification program. You can take the exam online and you should be supervised by a person that you select so, you have to choose a supervisor wisely in order to add credibility to your certificate. This does not add value to the certification though IMHO.

The examination consists of 70 multiple choice or true/false questions about PHP (it requires fundamental knowledge of SQL too) and you have 70′ (minutes) to complete the test. To become certified, you have to have 75% of the questions answered correct and, if you get more than 95% you get an excellency degree. The service will inform you about your pass/fail status immediately after the end of the examination and if you have passed the exam, you will be sent a PHP developer certificate. Your supervisor should sign the certification which, you can use to prove your PHP knowledge. You can verify your certification online at a unique URL that the certificate points to.

The w3schools certification costs $75 and you can pay by Paypal or credit card.

Brainbench

bbBrainbench is dedicated to helping organizations use assessment science to predict employee success. Using the Brainbench assessment platform, companies improve hiring and retention, boost training success, enhance customer satisfaction, and increase profitability. One of the ways to do this, is by certifying several aspects of job criteria. Brainbench has tests for you to certify your knowledge for nearly anything from aerospace to programming and of course, for PHP.

You can take the examination online for $49.95 .

ExpertRating

hd03ExpertRating is an ISO 9001:2000 company that offers hundreds of popular certifications and tests which are suitable for students, professionals, job seekers and companies.

ExpertRating tests consist of timed, multiple choice questions with one or more correct answer/s to each question. Each test covers basic to advanced questions on each topic. The test taker should keep in mind that the knowledge of applied skills gained through real work experience is emphasized rather than theoretical knowledge. For achieving certification the test taker must score at least 50% marks. Clearing the test with a score of 80% or more will be credited as a distinction and mentioned on the certificate of accomplishment.

To get PHP certified with ExpertRating, you have to pass a 40 multiple choice questions test. You have 45 minutes to answer all questions. The certificate costs $9.95

OST

OST_LogoIn OST’s unique online Learning Sandbox®, students have access to their own web programming and Unix shell-based database environments where they will apply new skills as they are presented by completing real-world projects.

Completion of the 4-course series earns students a Certificate of Professional Development from the University of Illinois Office of Continuing Education. All courses are certified by the University of Illinois Department of Computer Science, and students receive Continuing Education Credits upon completion of each course in the series.

The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux MySQL platform.

The certificate costs $398

What does it take?

To become a certified PHP developer, besides PHP knowledge, you might need to be aware of :

  • HTML
  • SQL (MySQL most commonly)
  • Web administration
  • XML

Why?

Because as stated on the top of this post, being a great PHP developer sometimes might not be enough. Sometimes, you have to prove your knowledge to an employer to get the job and, being a PHP certified developer is one great way. Employers from around the world can find you easier since, most of the times, your name will be listed as a PHP developer on pages associated with employers.

OK I like it. Where do i start?

Here is a good list of tests and quizzes to help you get accustomed with most of the exams above:

Orginal From

Posted in PHP | 1 Comment »

25 New & Useful PHP Techniques & Tutorials

Posted by nsdhami on October 14, 2009

PHP is the most popular and widely accepted server side scripting language among developers due to its easy to learn nature, free of cost and its large ever increasing helpful community. Here are 25 useful PHP techniques and tutorials, most of which have been published only in this year. More …

Posted in PHP | Leave a Comment »

PHP Quizes

Posted by nsdhami on September 25, 2009

PHP Quiz part 1

Simple things of PHP can be just as fun as the advanced things in
PHP!
To prove that I wanted to make a small quiz, and here it is.

Below you’ll see 10 pieces of PHP5 code, the goal is to figure
out the code and know the output before you actually run it.
Have fun!

Comment and closing tag

<?php //
Without cheating.. What will you see when you run this single line of
?\?> php code

Echo print and get what

<?php
  // What do you expect from this ?
  echo print( 1 ); ?>

What wil eval to true

 <?php
  // How many times will we get ‘true’ ?

  $boolean  = false;
  echo ($boolean) ? ‘true’ : ‘false’;

  $boolean  = ‘0′;
  echo ($boolean) ? ‘true’ : ‘false’;

  $boolean  = ‘00′;
  echo ($boolean) ? ‘true’ : ‘false’;

First a cast, then an increment, but what is shown?

<?php
  // What number will you get to see?
  $integer = (int) ‘PHP’;
  echo ++$integer;

Float boat

 <?php
        // What number will be
output?
        $a = 0.1 + 0.7;
        echo (int) ($a*10) + 1 ;

Array key fun

 <?php

        $a[ 1 ] = “The one”;
        $a["a"] = “The second”;
        $a["1"] = “The who?”;
        $a["A"] = “CaSe FuN”;
        $a["01"]= “The last”;

        echo count($a); // How many
do you expect?

Array count

 <?php

        $one    =
range(1, 3);
        $two    = 7;
        echo count($one) +
count($two); // How much will the be?

Array key existence

 <?php

        // Will it be isset?

       
$a             
= range(10,20);
       
$a[11]          = “The one
and only”;
       
$a['11']        = null;

        unset($a[1]);
        if (isset($a[11])) {
               
echo “Yes, it’s isset!”;
        } else {
               
echo “No, it’s not isset.”;
        }

Array evil sort

 <?php

       
$a      = array(0, 1, 0.1=>’a',
1.1=>’A');
        sort($a);

        echo count($a); // Is it what
you expected?

Array reference voodoo

<?php

        $a =
array(‘i’,'b’,'b’,'q’,'b’,'!’);
        foreach($a as
&$value)  {}
        foreach($a as
$value)   {}

        echo   
str_rot13( implode(”, $a) ); // how many letters
?

PHP Quiz part 2

A short quiz this time, but that doesn’t make it less fun. Do you
know the answer to all of them? Get a cup of coffee and kill 10 minutes
with round two…

As always, think of the answer before you execute the code or
look it up. You can find round one here.

Array pointer

What will the output be ?
$array = range(0,5);
next($array);
foreach($array
as $v) {
  echo $v;
}
 

ArrayAccess and isset fun

isset or not isset, thats the question.
$a          = new ArrayObject;
$a[‘fubar’]
= NULL;
$null       = NULL;

if (isset($null))
{
        echo 1;
} else {
        echo 2;
}

if (isset($a[‘fubar’])) {
        echo 1;
} else {
        echo 2;
}

if (array_key_exists(‘fubar’,
$a)) {
        echo 1;
} else {
        echo 2;
}

Typo?

The output might be confusing..
array(4>‘a’)

References

How many notices will be thrown?
error_reporting(E_ALL);
function a( & $array) {}
function b($array) {}
a($array);
b($array)

OR or || – operator precedence

What will the output be?
echo
( 1
? 0 : 1
or 1 ),
( 1
? 0 : 1
|| 1 );
 

Nesting structures

Will this error, or not?
if (1):
    echo ‘one’;
    if(2) {
        echo ‘two’;
    }
else:
    echo ‘not
one’
;
endif;

PHP Quiz part 3

Welcome to another part of the PHP Quiz series, again some
interesting questions to crack your brain about. If you have some nice
additions or questions, be sure to leave a comment. Enjoy part three!

As always, think of the answer before you execute the code or
look it up. You can find round two here.

Unset cast

What is the type of $a and what is the type of $b
$a = “A”;
$b = (unset) $a;
var_dump($a,
$b);
 

Form fun

What will the output be?
<form method=“post” action=“” enctype=“text/plain”>
    <input name=“search”
type=“text”>
    <input type=“submit”>
</form>
<?php
        error_reporting( E_ALL );
        echo (string) filter_input(INPUT_POST, ’search’);
?>
 

Fun with strings

Strings in PHP are versatile, but how versatile are they… What
will the output be?$juggling = “Itffkhmf”;

$rox = “Spy”;

$b = $c
= “”;
for ($i=0;
$i<strlen($juggling); $i++) {

    $b .= $juggling[
$i ];

    $b++;
}
for ($i=0;
$i<strlen($rox); $i++) {

    $c .= $rox[
$i ];

    $c–;
}

var_dump( $b,
$c );

Referenced returning

Do you know the referencing details? What will the output be?class RR {
  public $varA = “z”,
         $varB
= “z”,
         $varC
= “z”;

  function
& getA() {
    return $this->varA;
  }

  function
& getB() {
    return $this->varB;
  }

  function
getC() {
    return $this->varC;
  }
}

$rr = new RR;

// Option A,
method only

$a = $rr->getA();

$rr->varA = “a”;

// Option B,
both method and assign

$b = & $rr->getB();
$rr->varB = “b”;

// Option C,
assign only

$c = & $rr->getC();
$rr->varC = “c”;

var_dump($a,
$b, $c);

For what it’s worth

$obj    = new stdClass;
$int    = 1;
$string = “a”;

echo
($obj
* 2),
($int
* 3),
($string
* 4);

Global precedence

function multiply($b) {

    $a = 100;
    global $a;

    return $a * $b;
}

echo
multiply(100);
 

Making the (seemingly) impossible, possible

Don’t use codepad to figure out whats happening, since that gives
a big hint right away. Try it on the CLI and think about what is
happening first.class A {
  private $A;
}

class B extends A {
  public $AA;
}

// How many
keys, and what are the keys?

var_dump( (array) new B()
);
 

Posted in PHP | Leave a Comment »

Optimizing PHP

Posted by nsdhami 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 …

Posted in PHP | Leave a Comment »

Create daemons in PHP

Posted by nsdhami 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 nsdhami on September 3, 2009

Posted in PHP | Leave a Comment »

Solutions To Session Attacks

Posted by nsdhami 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 nsdhami 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 nsdhami 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 nsdhami 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 | Leave a Comment »