Friday, November 27, 2009

SimpleXML does not parse text inside CDATA tags in an XML.

SimpleXML does not parse text inside CDATA tags in an XML.

Consider the XML below:

$str = '';
$str.='some text goes here';

To parse it we use following syntax:

$xml = simplexml_load_string($str);

On printing it outputs:

SimpleXMLElement Object
[childNode] => some text goes here

Thats OK. Now the same xml but this time the text is enclosed in CDATA tags.

$str = '';

On printing this gives following output:

SimpleXMLElement Object
[childNode] => SimpleXMLElement Object


Yes its empty. This is because SimpleXML does not parse CDATA tags. All data enclosed within CDATA is ignored by SimpleXML parser.
Solution: Set the 3rd parameter to LIBXML_NOCDATA while parsing.

simplexml_load_string(simplexml_load_file too) actually takes 3 parameters.

* The string to parse
* Optional parameter – to return an object of class specified in this parameter. (By default it returns a SimpleXMLElement Object)
* Also optional – libxml parameters can be specified as options. This option provides the solution to our CDATA problem

Provide the 3rd parameter LIBXML_NOCDATA and SimpleXML will consider CDATA nodes as text nodes and will parse them.

$xml = simplexml_load_string($str,'SimpleXMLElement', LIBXML_NOCDATA);

This will output as desired:

SimpleXMLElement Object
[childNode] => some text goes here

Please note that using the third parameter requires PHP >=5.1 compiled with libxml.

in reference to: Google Sidewiki (view on Google Sidewiki)

Wednesday, November 11, 2009

Find how many number of result of your site on google

/* return result number */
function get_google_results($domain = '')
// get the result content
$content = file_get_contents(''.$domain);

// parse to get results
$result = get_match('/Results <b>(.*)from/isU',$content);

// echo $result;

// split the results
$split1 = explode('of about',$result);

// return result
return $split1[1] ? strip_tags($split1[1]) : 0;

/* helper: does the regex */
function get_match($regex,$content)
return $matches[1];

/* do it! */
echo ' '.get_google_results(''); // 164
//echo ' '.get_google_results(''); // 164

Tuesday, November 10, 2009

How to upload file with FTP in PHP


prepare a form similiar to this and have it call the below file
echo '<form action="image_upload.php" method="post" enctype="multipart/form-data">';
echo 'Click the Browse button to find the file you wish to upload';
echo '<input type="file" name="imagefile">';
echo '<INPUT TYPE="submit" name="upload" value="upload">';
echo '</form>';
*** <input type="file" name="imagefile"> ***
*** with the above tag declared in the calling form ***
*** the variable name is $imagefile and the available properties are ***
*** $imagefile :name of the file as stored on the temporary server directory ***
*** $imagefile_name :filename.extension of the file as on the users machine ***
*** $imagefile_size :size in bytes of the file ***
*** $imagefile_type :the type of file image/gif image/jpg text/html etc.... ***
*** ***
//change these values to suit your site
//$web_location is needed for the file_exists function, the directories used by FTP
//are not visible to it will will always return not found.

//build a fully qualified (FTP) path name where the file will reside

// connect, login, and transfer the file
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$upload = ftp_put($conn_id, $destination_file, $imagefile, FTP_BINARY);

//use ftp_site to change mode of the file
//this will allow it be visible by the world,
$ch=ftp_site($conn_id,"chmod 777 ".$destination_file);
// close the FTP stream

//verify file was written
if (file_exists($web_location))
echo "file was uploaded as $web_location";
echo "Could not create $web_location";
//end if


Thursday, September 10, 2009

Creates a backup of a MySQL in SQL format.

echo "Error1";exit;

echo "Error2";exit;
if (!function_exists('mysql_dump')) {
function mysql_dump1($database) {
$query = '';
$tables = @mysql_list_tables($database);
while ($row = @mysql_fetch_row($tables)) { $table_list[] = $row[0]; }
for ($i = 0; $i < @count($table_list); $i++) {
$results = mysql_query('DESCRIBE ' . $database . '.' . $table_list[$i]);
$query .= 'DROP TABLE IF EXISTS `' . $database . '.' . $table_list[$i] . '`;' . lnbr;
$query .= lnbr . 'CREATE TABLE `' . $database . '.' . $table_list[$i] . '` (' . lnbr;
$tmp = '';
while ($row = @mysql_fetch_assoc($results)) {
$query .= '`' . $row['Field'] . '` ' . $row['Type'];
if ($row['Null'] != 'YES') { $query .= ' NOT NULL'; }
if ($row['Default'] != '') { $query .= ' DEFAULT \'' . $row['Default'] . '\''; }
if ($row['Extra']) { $query .= ' ' . strtoupper($row['Extra']); }
if ($row['Key'] == 'PRI') { $tmp = 'primary key(' . $row['Field'] . ')'; }
$query .= ','. lnbr;
$query .= $tmp . lnbr . ');' . str_repeat(lnbr, 2);
$results = mysql_query('SELECT * FROM ' . $database . '.' . $table_list[$i]);
while ($row = @mysql_fetch_assoc($results)) {
$query .= 'INSERT INTO `' . $database . '.' . $table_list[$i] .'` (';
$data = Array();
while (list($key, $value) = @each($row)) { $data['keys'][] = $key; $data['values'][] = addslashes($value); }
$query .= join($data['keys'], ', ') . ')' . lnbr . 'VALUES (\'' . join($data['values'], '\', \'') . '\');' . lnbr;
$query .= str_repeat(lnbr, 2);

return $query;

Monday, August 31, 2009

Mysql function run in the environment of PHP

Mysql function run in the environment of PHP

Saturday, June 6, 2009

Lower Case an Array

Lower Case an Array

Here is an example of how to force all values in array tolower case. This could, of course, be used in the same way to make the array UPPERCASE or do anything else you wish to the array values. Note the that the string is passed to the array by reference. This is so the actual array values are manipulated.


/*** an array of mixed case words ***/
$array = array('MAC', 'Apple', 'osX');

* @Lower case an array
* @param ref string $string
* @return string
function lower(&$string){
$string = strtolower($string);

/*** apply the lower function to the array ***/

foreach($array as $value){
echo $value;

Wednesday, April 29, 2009


if (!isset($_SESSION['timeout_idle'])) {
$_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME; //set time at the first time of writing script
} else {
if ($_SESSION['timeout_idle'] < time()) {
//destroy session if session time is less the what we have set the time
} else {
$_SESSION['timeout_idle'] = time() + MAX_IDLE_TIME; // if continue working on similar site then increase the time of script

PHP- Remove Special Character during website

// put this code on the top of the page or in your config file. You will never see the special character on that page/website(if you used config on the top then it work on whole website)

header("Content-type: text/html; charset=UTF-8");
ini_set('mbstring.internal_encoding', 'UTF-8');

Tuesday, April 28, 2009


// Assuming the above tags are at
$tags = get_meta_tags('');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // documentation
echo $tags['description']; // discription
echo $tags['geo_position']; // 49.33;-86.59

var_dump($tags); // get all values


Friday, April 24, 2009

Secure file download from PHP server

< ?php
// local file that should be send to the client
$local_file = 'filename';
// filename that the user gets as default
$download_file = 'if_u_wanna_to_change_file_name_i._e._uploade_then name';
// I u do not want to change name then wrtre
//$download_file = 'if_u_wanna_to_change_file_name_i._e._uploade_then name';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

// flush content
// open file stream
$file = fopen($local_file, "r");
while(!feof($file)) {

// send the current file part to the browser
print fread($file, round($download_rate * 1024));

// flush the content to the browser

// sleep one second

// close file stream
else {
die('Error: The file '.$local_file.' does not exist!');
? >

PHP5 Tutorial - Defining Attributes of a PHP5 Class

In this tutorial you will learn about class attributes and how to declare & use them in PHP5 classes.

Definition of an class attribute
An attribute is also know as data members and is used to hold data of a class. The data that it holds are specific to the nature of the class in which it has been defined. For example, a Customer class would hold data related to a customer, an Order class would hold data related a an order.

Defining an attribute is as easy as declaring a variable within the body of the class. At the time of declaring a data member/variable within the body of the class, it is also possible to assign a default value to the attribute or data member.

Attributes can either be public, private or protected - the default being public. These are called Access Specifiers. You will learn more about access specifiers in PHP5 OOPS tutorials ahead.

Example Code:

class Customer {
private $first_name, $last_name;
private $outstanding_amount = 0; //example of default value

public function getData($first_name, $last_name) {
$this->first_name = $first_name;
$this->last_name = $last_name;

public function printData() {
echo $this->first_name . " : " . $this->last_name;

$c1 = new Customer();

In the above example $first_name, $last_name and $outstanding_amount are data members or attributes of the class Customer. Of these attributes, $outstanding_amount has a default value of zero assigned to it. This means that when an object of the Customer class has been created, $first_name and $last_name will be blank whereas; $outstanding_amount will be initialized with default value of zero.

Let’s take a problem statement and define a PHP5 Class for it.

Problem Statement:
Define a class to encapsulate Student. The data required to be captured is Student’s first name, last name, date of birth, address and telephone number.


class Student {
public $first_name;
public $last_name;
public $date_of_birth;
public $address;
public $telephone;

In the above example $first_name, $last_name, $date_of_birth, $address and $telephone are all data members of class Student. These data members define the data that one Student Object will store. Therefore, you can create two objects of a Student class having different data as follows:

//creating an object $s1 of Student class and assigning data
$s1 = new Student();
$s1->first_name = "Sunil";
$s1->last_name = "Bhatia";
$s1->date_of_birth = "01/01/1900";
$s1->address = "India";
$s1->telephone = "9999999999";

//creating an object $s2 of Student class and assigning data
$s2 = new Student();
$s2->first_name = "Vishal";
$s2->last_name = "Thakur";
$s2->date_of_birth = "01/01/1910";
$s2->address = "USA";
$s2->telephone = "8888888888";

In the above example, we create two objects of the Student class $s1 and $s2. Both these objects have their own memory space within which they store their respective data. Because each data member is ‘public‘ you can directly access the data members of the Student Class using the arrow operator (reference operator) i.e. $s1->first_name = “Sunil”; You will learn more about public, private and protected in the PHP5 tutorials ahead on Access Specifiers.

The diagram below explains the above example:

PHP5 Tutorial - Learn to Create a PHP5 Class Object

In the earlier PHP5 OOPS tutorial you learnt how to create a class in PHP5. In this tutorial you will learn how to create an object of a PHP5 class. But before we begin, lets understand what is an object.

Definition of an Object
An object is a living instance of a class. This means that an object is created from the definition of the class and is loaded in memory. A good analogy to understand this is to compare objects with humans - and understand that all of us (you and I) are objects. If God wants to send a human to earth, what is easy for Him to do? Create and define properties and attributes of each human separately or create a one time template and generate objects out if it. Therefore, this onetime template is a Class and you, I & everyone in this world is an object - that is a living instance of class Human.

Creating Objects in PHP5 Class

To create an object of a PHP5 class we use the keyword new. Below is the syntax style of how to create objects in PHP5:

        $obj_name = new ClassName();

In the above syntax style, $obj_name is a variable in PHP. ‘new’ is the keyword which is responsible for creating a new instance of ClassName.

Look at the example below:

class Customer {
private $first_name, $last_name;

public function getData($first_name, $last_name) {
$this->first_name = $first_name;
$this->last_name = $last_name;

public function printData() {
echo $this->first_name . " : " . $this->last_name;

$c1 = new Customer();
$c2 = new Customer();

In the above example $c1 and $c2 are two objects of the Customer Class. Both these objects are allocated different blocks in the memory. Look at the diagram below:

Therefore, an object is a living instance of a class. Each object / living instance has its own memory space that can hold independent data values.

PHP5 Tutorial OOPS - PHP5 Class Access Specifiers - public, private and protected

In the earlier tutorials we have witnessed keywords like public, private and protected. These are nothing but access specifiers. So, lets understand what access specifiers are.

Definition of Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be public, private or protected.

Why do we need Access specifiers
Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world.

Explanation of each access specifier

1. Private
2. Protected
3. Public

1. Private
A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access them. Look at the example below:

class Customer {
private $name;

public function setName($name) {
$this->name = $name;

public function getName() {
return $this->name;

$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; //error, $name cannot be accessed from outside the class
//$name can only be accessed from within the class

echo $c->getName(); //this works, as the methods of the class have access
//to the private data members or methods

In the above example, echo $c->name will give you an error as $name in class Customer has been declared private and hence only be accessed by its member functions internally. Therefore, the following line echo $c->getName() will display the name.

2. Public
A public access specifier provides the least protection to the internal data members and member functions. A public access specifier allows the outside world to access/modify the data members directly unlike the private access specifier. Look at the example below:

class Customer {
public $name;

public function setName($name) {
$this->name = $name;

public function getName() {
return $this->name;

$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; // this will work as it is public.
$c->name = "New Name" ; // this does not give an error.

In the above example, echo $c->name will work as it has been declared as public and hence can be accessed by class member functions and the rest of the script.

3. Protected
A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script). We can also say that a protected data member is public for the class that declares it and it’s child class; but is private for the rest of the program (outside world). Look at the example below:

class Customer {
protected $name;

public function setName($name) {
$this->name = $name;

public function getName() {
return $this->name;

class DiscountCustomer extends Customer {

private $discount;

public function setData($name, $discount) {
$this->name = $name; //this is storing $name to the Customer
//class $name variable. This works
// as it is a protected variable

$this->discount = $discount;

$dc = new DiscountCustomer();
$dc->setData("Sunil Bhatia",10);
echo $dc->name; // this does not work as $name is protected and hence
// only available in Customer and DiscountCustomer class

In the above example, echo $dc->name will not work work $name has been defined as a protected variable and hence it is only available in Customer and DiscountCustomer class.

You will learn more about inheritance later in this tutorial series. You should revisit this tutorial and read more on the protected section again when you understand inheritance better.

Important Note of Access Specifier in PHP5
In PHP5, access specifiers are public by default. This means that if you don’t specify an access specifier for a data member or method then the default ‘public’ is applicable.

PHP5 Tutorial - Learn to create a PHP5 Class

Before we begin learning how to create PHP5 Class, lets first understand the meaning of a class in object oriented programming practices.

Definition of a Class

A class is user defined data type that contains attributes or data members; and methods which work on the data members. (You will learn more about data members and methods in following tutorials. This tutorial focuses only on learning how to create a Class in PHP5)

To create a class, you need to use the keyword class followed by the name of the class. The name of the class should be meaningful to exist within the system (See note on naming a class towards the end of the article). The body of the class is placed between two curly brackets within which you declare class data members/variables and class methods.

Following is a prototype of a PHP5 class structure

class  {



Example of a Class:

class Customer {
private $first_name, $last_name;

public function getData($first_name, $last_name) {
$this->first_name = $first_name;
$this->last_name = $last_name;

public function printData() {
echo $this->first_name . " : " . $this->last_name;

In the above program, Customer is the name of the class and
$first_name/$last_name are attributes or data members. getData() and
printData() are methods of a class. We will discuss more about
attributes and members in the upcoming articles on PHP5 OOPS Tutorials series.

You can read more about private, public and protected in this tutorial on Access Specifiers

Naming Conventions

Naming Convention for Class:
As a general Object Oriented Programming practice, it is better to name the class as the name of the real world entity rather than giving it a fictitious name. For example, to represent a customer in your OOAD model; you should name the class as Customer instead of Person or something else.

Naming Conventions for Methods:
The same rule applies for class methods. The name of the method should tell you what action or functionality it will perform. E.g. getData() tells you that it will accept some data as input and printData() tells you that it will printData(). So ask yourself what you would name a method which stores data in the database. If you said storeDataInDB() you were right.

Look at the manner in which the method storeDataInDB() has been named. The first character of the first word of the method is lower case i.e. ‘s‘tore. For rest of the words in the function viz Data/In/DB have been named as first character Uppercase and the remaining characters of the words as lower case i.e. ‘D’ata ‘I’n ‘D’B. Therefore it becomes storeDataInDB()

Naming Convention for Attributes:
Attributes of a class should be named on the basis of the data that they hold. You should always give meaningful names to your attributes. For attributes you should split the words with an underscore (_) i.e. $first_name, $last_name, etc.

In the next tutorial we will see how to create objects in PHP5.

Feel free to write comments if you need more examples or if you need to ask a question on PHP5 Class. You can also subscribe to my notification service to be informed as an when a new tutorial article goes online. Subscribe Below

PHP Interview Questions

PHP Interview Questions

1. What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?

On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.

On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.

GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

2. Who is the father of php and explain the changes in php versions?

Rasmus Lerdorf for version changes go to Marco Tabini is the founder and publisher of php|architect.

3. How can we submit from without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example:

4. How many ways we can retrieve the date in result set of mysql Using php?

As individual objects so single record or as a set or arrays.

5. What is the difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array.

6. What is the difference between $message and $$message?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains "var", $$message is the same as $var.

7. How can we extract string ‘ ‘ from a string ‘http://info@a…’ using regular _expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern. For example: preg_match("/.*@(.*)$/","",$data); echo $data[1];

8. How can we create a database using php and mysql?

PHP: mysql_create_db()
Mysql: create database;

9. What are the differences between require and include, include_once?

File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.

10. Can we use include ("abc.php") two times in a php page "makeit.php"?

Yes we can include..

11. What are the different tables present in mysql, which type of table is generated when we are creating a table in the following
syntax: create table employee(eno int(2),ename varchar(10)) ?

Total 5 types of tables we can create


2. Heap

3. Merge

4. InnoDB


6. BDB
MyISAM is the default storage engine as of MySQL 3.23.

12. Functions in IMAP, POP3 AND LDAP?

Please visit:

13. How can I execute a php script using command line?

Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

14. Suppose your ZEND engine supports the mode Then how can u configure your php ZEND engine to support mode ?

If you change the line: short_open_tag = off in php.ini file. Then your php ZEND engine support only mode.

15. Shopping cart online validation i.e. how can we configure the paypals?

16. What is meant by nl2br()?

nl2br — Inserts HTML line breaks before all newlines in a string string nl2br (string); Returns string with ‘’ inserted before all newlines. For example: echo nl2br("god bless\n you") will output "god bless \n you" to your browser.

17. Draw the architecture of ZEND engine?

18. What are the current versions of apache, php, and mysql?

PHP: php5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1

19. What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other software programs, servers and operating systems?

All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language.

20. How can we encrypt and decrypt a data present in a mysql table using mysql?


21. How can we encrypt the username and password using php?

You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");
We can encode data using base64_encode($string) and can decode using base64_decode($string);

22. What are the features and advantages of OBJECT ORIENTED PROGRAMMING?

One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.


Traditional programming has the following characteristics:

Functions are written sequentially, so that a change in programming can affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.

Object-Oriented programming takes a radically different approach:

Code and data are merged into one indivisible item – an object (the term "component" has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around "date") The object would contain all information and functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday. It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system. The information within an object is encapsulated (or hidden) from the rest of the system.
A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages.
OO programming languages include features such as "class", "instance", "inheritance", and "polymorphism" that increase the power and flexibility of an object.

24. What is the use of friend function?

Friend functions
Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class whichnames them as a friend, as if they were themselves members of that class.
A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.

class mylinkage
mylinkage * prev;
mylinkage * next;

friend void set_prev(mylinkage* L, mylinkage* N);
void set_next(mylinkage* L);

mylinkage * succ();
mylinkage * pred();

void mylinkage::set_next(mylinkage* L) { next = L; }

void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

Friends in other classes

It is possible to specify a member function of another class as a friend as follows:

class C
friend int B::f1();
class B
int f1();

It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.

class A
friend class B;

Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

25. What are the differences between public, private, protected, static, transient, final and volatile?
element Class Interface
Data field Method Constructor
modifier top level nested top level nested
(outer) (inner) (outer) (inner)
final yes yes no yes yes no no
private yes yes yes no yes no yes
protected yes yes yes no yes no yes
public yes yes yes yes yes yes yes
static yes yes no no yes no yes
transient yes no no no no no no
volatile yes no no no no no no

26. What are the different types of errors in php?

Three are three types of errors:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although, as you will see, you can change this default behaviour.

2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behaviour is to display them to the user when they take place.

27. What is the functionality of the function strstr and stristr?

strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr("","@") will return "".
stristr() is idential to strstr() except that it is case insensitive.

28. What are the differences between PHP 3 and PHP 4 and PHP 5?

Go read the release notes at

29. How can we convert asp pages to php pages?

You can download asp2php front-end application from the site

30. What is the functionality of the function htmlentities?

Answer: htmlentities — Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

31. How can we get second of the current time using date function?

$second = date("s");

32. How can we convert the time zones using php?

33. What is meant by urlencode and urldocode?

urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25?. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.

34. What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system.
unset() makes a variable undefined.

35. How can we register the variables into a session?

We can use the session_register ($ur_session_var) function.

36. How can we get the properties (size, type, width, height) of an image using php image functions?

To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function

37. How can we get the browser properties using php?

38. What is the maximum size of a file that can be uploaded using php and how can we change this?

You can change maximum size of a file set upload_max_filesize variable in php.ini file

39. How can we increase the execution time of a php script?

Set max_execution_time variable in php.ini file to your desired time in second.

40. How can we take a backup of a mysql table and how can we restore it.?
Answer: Create a full backup of your database: shell> mysqldump –tab=/path/to/some/dir –opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir
The full backup file is just a set of SQL statements, so restoring it is very easy:

shell> mysql "."Executed";

41. How can we optimize or increase the speed of a mysql select query?

42. How many ways can we get the value of current session id?
session_id() returns the session id for the current session.

43. How can we destroy the session, how can we unset the variable of a session?
session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables

44. How can we destroy the cookie?
Set the cookie in past

45. How many ways we can pass the variable through the navigation between the pages?
GET or QueryString and POST

46. What is the difference between ereg_replace() and eregi_replace()?
eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

47. What are the different functions in sorting an array?
Sorting functions in PHP,

48. How can we know the count/number of elements of an array?
2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
interestingly if u just pass a simple var instead of a an array it will return 1.

49. What is the PHP predefined variable that tells the What types of images that PHP supports?

50. How can I know that a variable is a number or not using a JavaScript?

51. List out some tools through which we can draw E-R diagrams for mysql.

52. How can I retrieve values from one database server and store them in other database server using PHP?

53. List out the predefined classes in php?


54. How can I make a script that can be bilanguage (supports Eglish, German)?

You can change charset variable in above line in the script to support bilanguage.

55. What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

56. How can we send mail-using JavaScript?

NO! JavaScript can't email a form! but, there are alternatives to send the form data to an email address.

57. How can we repair a mysql table?

The syntex for repairing a mysql table is
This command will repair the table specified if the quick is given the mysql will do a repair of only the index tree if the extended is given it will create index row by row

58. What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.
Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

59. What is the maximum length of a table name, database name, and fieldname in mysql?

Database name- 64
Table name -64

60. How many values can the SET function of mysql takes?

Mysql set can take zero or more values but at the maximum it can take 64 values

61. What are the other commands to know the structure of table using mysql commands except explain command?

describe table_name;

Wednesday, April 15, 2009

PHP date difference

If you want to get the difference between to dates or time values, then you first need to get the values in the same format. The best way is to convert both dates into Unix timestamp format. In this case the date and time information is stored as an integer so we can calculate the difference easily. You can get the Unix timestamp in various ways as you can see below:

// Get current time
$date1 = time();
// Get the timestamp of 2006 October 20
$date2 = mktime(0,0,0,10,20,2006);
? >

Now as you have the values getting the difference is quite easy. However the result will be an integer value, but you probably want to get it in days, hours and minutes. To do so we need to convert back our int value into a usable date format. We know that the difference is in seconds so we can get how many full days it is. To get it we use the following code:

lt; ?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
echo "Differernce is $fullDays days";

We used the floor function as we want to get only the complete days. Besides this the 60*60*24 represents that a day has 24 ours and each hour has 60 minutes and each minute has 60 seconds.

As next step we need to get how many hours are still present in the remaining seconds. So from the original difference we need to remove the complete days in seconds and from the remaining value we can calculate the full hours similar to as we calculated the full days. Repeating these steps for minutes as well at the end we get the difference between the original dates. The complete calculation looks like this:

$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";

Tuesday, April 14, 2009

Thumbnail photo/image format .jpg, .gif, .png in PHP at the time of image upload

//define a maxim size for the uploaded images
define ("MAX_SIZE","2048");
// define the width and height for the thumbnail
// note that these dimensions are considered the maximum dimension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");

// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
//get image extension.
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))



//gets the dimmensions of the image

// next we will calculate the new dimensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimensions will be from the fixed ones
if($ratio1>$ratio2) {
else {

// we create a new image with the new dimensions

// resize the big image to the new created one

// output the created image to the file. Now we will have the thumbnail into the file named by $filename

//destroys source and destination images.

// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;

// This function upload the file.
function uploadimage($imagepath, $thumbpath){
if ($image)
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")&& ($extension != "gif"))
echo '<h1>Unknown extension!</h1>';
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server

//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1024)
echo '<h1>You have exceeded the size limit!</h1>';
//we will give an unique name, for example the time in unix time format
//the new name will be containing the full path where will be stored (images folder)
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
echo '<h1>Copy unsuccessfull!</h1>';
// the new thumbnail image will be placed in images/thumbs/ folder
// call the function that will create the thumbnail. The function will get as parameters

// checks if the form has been submitted
if(isset($_POST['Submit']) && !$errors )
uploadimage('images', 'images/thumbs');
echo "<h1>Thumbnail created Successfully!</h1>";


<form name="newad" method="post" enctype="multipart/form-data" action="">
<div><label>Image: </label><input type="file" name="image" ></div>
<input name="Submit" type="submit" value="Upload image">

Laravel Interview questions and answers

1. What is Laravel Laravel is free open source “PHP framework” based on MVC Design Pattern . It is created by Taylor Otwell. Laravel pro...