PHP

PHP Interview Questions and Answers

More interview questions and answers

How we use Simple \"die()\" statements error handling method in PHP?

Die() is used to display a message and exits the current script.

I have given you an example:

 In this we try to open a file. Suppose if that file does not exist,Then you might get an error like this \"fopen(R4R Welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\\PHPWelcome.php on line 2\".

 Now, we can handle this error with a die(\"File does not exist\") statement.

 So, if file does not exist then you might get an error like this, \"File does not exist\" which is much more easier to understand than the earlier code.

How we handle errors in PHP ?

In PHP we can handle errors easily. Because when error comes it gives error level with their respective line and send error message to the web browser. When we create any web application and scripts. We should handle errors wisely. Because when erros are not handled properly, they can make big hole in security. In PHP we handle errors by using these methods:

  1. 1.Simple \"die()\" statements
  2. 2.Custom errors and error triggers
  3. 3.Error reporting

How you can differentiate abstract class and interface?

There are some main difference between abstract class and interface class are given below:

1.In an abstract we can use sharable code where in the case of interface their is no facility to use sharable code.

2.Class in which we implement an interface class. All method that we use should be defined in interface. Where as class those extending an abstract while a class extending an abstract class they are may and may not be  defined methodsin the abstract class.

3.Methods in inheritance class should be declared as public whereas in abstract it can be protected as well as public.

 

How we can upload videos using PHP?

When want to upload videos using PHP we should follow these steps:

  1. First you have to encrypt the the file which you want to upload by using \"multipart-form-data\" to get the $_FILES in the form submission.
  2. After getting the $_FILES[\'tmp_name\'] in the submission
  3. By using move_uploaded_file (tmp_location,destination) function in PHP we can move the file from original location.

How we use Custom errors and error triggers error handling methods in PHP?

In Custom errors and error triggers,we handle errors by using self made functions.

1. Custom errors : By using this we can handle the multiple errors that gives multiple message.

Syntax:set_error_handler(\\\"Custom_Error\\\");

In this syntax if we want our error handler to handleonly one error than we write only one argument otherwisefor handle multiple errors we can write multiple arguments.

Example:Error: \"[$errorno] $errorstr\"; 

set_error_handler(\\\"custom_Error\\\"); //set error handler like this

echo($verify);?> //trigger to that error

2.Error trigger : In PHP we use error trigger to handlethose kind of error when user enter some input data.If data has an error than handle by error trigger function.

Syntax: trigger_error();

Example: In this trigger_error function generate error when i isless than or greater than 1.

How we use Error logging method in PHP?

In PHP,by default an error log send to the server\'s logging system or a file.By using error logging we can send and error log to the specific file or a remote destination.

Example.In this we send a mail to our self with error message. And end the script when error comes.

Error

[$errno] $errorstr\";

echo \"program has been notified\"; 

error_log(\"Error: [$errorno] $errorstr\",1, \"abc@xyz.com\",\"From: program@xyz.com\");

//set error handler

set_error_handler(\"customError\",E_USER_WARNING);

//trigger error

$i=0;

if ($i<=1) 

{

 trigger_error(\"I should be greater than 1\", E_USER_WARNING); 

}

Output:

[512] I should be greater than 1//Output of the code

Error: [512] I should be greater than 1 // error log recieved by our mail

What is .htaccess file and how to use them?

.htaccess is a file not an extension. This file is used to take on actions in the directory it is placed in via famous server called Apache web server. It provides various facilities including redirect functionality, if error 404 doesn\'t work then provides error document and password protection.


Example of a .htaccess file     

  •      AuthName \"Feed any member\'s name\"
  •      AuthUserFile /path/to/password/file/.htpasswd
  •      AuthType Basic
  •      require valid-user
  •      ErrorDocument 401 /error_pages/401.html
  •      AddHandler server-parsed .html

How to use it:
  1. Create a .htaccess file.
  2. Upload the file in ASCII mode.
  3. Upload the file in the directory which you want it to take over.

What is the substitution of submit in PHP?

We can do that by using one these of methods:

1.By using JavaScript- document.formname.submit();

2.By using CURL functions

3.By using header header(\"location: page.php\")

Example:

<?php

$i=1;

if($i==0)

{

<script> document.form1.submit();</script>

}

else

{

header(\"location:www.r4r.co.in\");

}

?>

What is the difference b/w PHP4 and PHP5?

The main difference b/w PHP4 and PHP5 are given below:

1.Generally,Both are same. PHP5 is a new version of PHP4. So,PHP5 has some improvement in design, security, and stability.

2.OOPS is used in PHP4 as well, with the difference that in PHP5 things are a little more evaluated.So, In PHP4 safety modes for classes (public, private) are not accepted.

What is the difference between $i and $$i?

The main difference between $i and $$i is that $i is an variable where $$i is an reference variable. 

Example:$variable=\"welcome\";$welcome=\"abhi\"; 

Output:$variable=welcome;$$variable=abhi;

What is the significance of destructor in PHP?

In PHP their is an destructor function which is to be called when an object is deleted.We use destructor function( _destruct() ).Which does not have any parameters.


 Example:public function __destruct() { print \"{$this->Name}n\";

What is the answer of following code echo 1< 2 and echo 1 >2 ?

Output of the given code are given below:

echo 1<2    output: 1

echo 1>2    output: no output

What do you understand about Magic Code in PHP?

In PHP we use some special type of character called Magic Code.

Magic Code was introduced to help newbie of programming in writing bad SQL codes. But later it has become vulnerable to SQL injection attacks.

Some magic codes are,

single quote( \' )

double quote( \" )

amperson ( & )


We can escape magic code using backslash(/).

what are the constant value in PHP?can we write them without $ symbol?

Constant values are those values which are once defined then cannot be changed.Unlike variables constants are global by default. 

Syntax: define(\"name\",\"value\",\"Case sensitive or not\");

name- describes the name of the constant

value- its respective value

case sensitive- Optional, by default it is false

Yes,we can write constant value in PHP without $ symbol.

Example

define(\"CONSTANT\",\"R4R Welcomes You\");

echo \"CONSTANT\";

output:R4R Welcomes You

What is the main difference between include_once() and require_once() in PHP?

The main difference between include_once() and require_once() is that, In PHP if file does not exist and specified with include_once() it gives show warning message or non-fatal error. And the statements following it are still be executed.

Where as if we specified file as require_once() it giver a fatal error. And the statements following it are not executed.

How can we find out the name of the current executing file?

We can get the name and path of the current executing file name by using SCRIPT_NAME

Example:

$file=$_SERVER[\'SCRIPT NAME\'];

echo\"$file\";

If the file name is sample.php and it is stored in myHome directory then the output would be:

Output: 

myHome/sample.php

How we can get the value of current session id?

We can get the value of our current session id by using session_id().

It returns the value of our current session id.

Apart from this we can also make use SID in PHP6

Which type of inheritance exists in PHP?

PHP supports Multi-level inheritance.It doesn\'t support multiple inheritance or the famous diamond problem. But using interface  we can achieve multiple inheritance in PHP.  

How we use ereg_replace() and eregi_replace() in PHP?

The main difference b/w ereg_replace and eregi_replace() is that,eregi_replace is case sensitive

Example:In eregi_replace() it think both \'welcome\' and \'WeLCome\' are different. 

Where as ereg_replace() is not case sensitive.

Example:In ereg_replace() it think both \'welcome\' and \'WeLCome\' are same.

What do you understand from Implode and Explode functions?

The main difference between Implode and Explode functions is that We use Implode function to convert the array element into string where each value of array is separated by coma(,).

Example:output:First_Name,Email_Id,Phone_No 

We use Explode function to convert the string value those are separated with coma(,) into array.

Example:output:First_NameEmail_IdPhone_No

Can we submit a form without submit button?

Using JavaScript we can submit a form without submit button.

Example:document.FORM_NAME.action=\"Welcome.php\";

document.FORM_NAME.submit();//this is used to submit the form

Can I develop our own PHP extension? If yes, how?

Yes, we can develop a PHP extension like this:

Example: To save this file as .php extention

What do you understand by nl2br()?

nl2br() function stands for new line to break tag.

Example: 

echo nl2br(\"R4R Welcomes\\nYou\"); 

Output:

 R4R Welcomes<br \\> 

you

How do you understand about stored procedure,Triggers and transaction in php?

Below I have given how stored procedure,Triggers and transaction work in PHP: 


1.Stored Procedure: It is combination of some SQL commands it is stored and can be compiled.Suppose that when user is executed a command than user has don\'t need to reissue the entire query he can use the stored procedure.Basically main reason to use the stored procedure is that using this we can decrease the time of reissue of that query. Because work done on server side is more than the work done on application side.

2.Trigger: Trigger is a stored procedure.This is used to work stored procedure effectively.It is invoked when a special type of event comes.To effectively understand this i have given you a example. 

When we attach a trigger with stored procedure than when we delete a record from transaction table than will automatically work and delete the respective client from client table.

3.Transaction: Transaction is that in which particular amount of data goes from the a client to the another client.We maintain the transaction record into a table called transaction table.

What function we used to change timezone from one to another ?

I have given you a function using this we can change a timezone into another timezone.date_default_timezone_set() function 

Example: 

date_default_timezone_set(\'America/Los_Angeles\');

date_default_timezone_get() //function to get the default timezone .

How we use array_search() in PHP?

When we use array_search() function if it found the particular value than it will return index corresponding to array value.

Example:

$Emp_name_array= array(0 => \'vivek\', 1 => \'umang\', 2 => \'shrish\', 3 => \'jalees\');

$key = array_search(\'umang\', $Emp_name_array); // return $key = 1; 

$key = array_search(\'vivek\', $Emp_name_array);  // return $key = 0;

 ?>

How to print in php with out using . or *?.

I have given you a example which definitely solved your query.
Example:
<?php
print \"\\\";
?>
output:
\\

How you differentiate among sort(), asort() and Ksort()?

sort() is a function used to sorts an array in ascending order. 

  1. asort() is a function  used to sort the associative array in ascending order with respect to their assigned value.
  2. ksort() is a function used to sort the associative array in ascending order with respect to their key value.

Tell me about PHP operator?

PHP provide us various operator. 

These are: 

1.Arithmetic Operator 

2.Assignment Operator 

3.Comparison Operator 

4.logical Operator 


1.Arithmetic Operator:Some arithmetic operators are given below:

Addition(\'+\') m+4 , 8(given m=4)

Subtraction(\'-\') m-4, 4(given m=8) 

Multiplication(\'*\') m*4, 8(given m=2) 

Division(\'/\') m/4, 2(given m=8) 

Modulus (division remainder)(\'%\') m%2, 1(given m=3) 

Increment(\'++\') m++, m=5(given m=4) 

Decrement(\'--\') m--, m=6(given m=5) 


2.Assignment Operator: Some assignment operations are given below:

 = m=n -= m-=n or m=m-n *= m*=n or m=m*n/= m/=n or m=m/n.= m.=n or m=m.n%= m%=n or m=m%n+= m+=n or m=m+n 


3.Comparison Operator:Some comparison operators are given below:

==(is equal to) 2==5returns false 

!=(is not equal to) 2!==5returns true 

>(is greater than) 2==5returns false

<(is less than) 2==5returns true

>=(greater than or equal to) 2==5returns false 

<=(is less than or equal to) 2==5returns true 


4.Logical Operators:Some logic operators are given below:

&&(and) (m<4 && n>2)returns true(given m=3,n=5) 

||(or) (m=4 && n=4)returns false(given m=5,n=6) 

!(not) !(m==n)returns true(given m=2,n=3)

How to declare data types in PHP?

Data type that we used in PHP are given below: 

1.Numeric

2.Boolean 

3.Array  

4.String  

5.Object

6.Reference

7.Float

We do not need to declare data type in PHP but we can get the type of a defined variable via function called var_dump();

Example:

$x=1000;

var_dump($x);

Output:

int(1000)

What is the use of strlen() and strpos() functions?

strlen() function is used to find out the length of the given string.

Example: 

$sample=\"Hello\";

echo strlen($sample);

output: 5 

strpos() function is used to match a character or word from the given string.And return the position of the character or word. 

Example:echo strpos(\"I am working as a intern in ycd\",\"ycd\"); 

output: 27

How we use if..else and elseif statement in PHP?

If..else statement is used where we want to execute some code if condition is true otherwise execute some other code. 

Syntax

if (condition) 

code to be executed;//when condition is true 

else 

code to be executed;//When condition is false 

Example:Elseif statement is used where we want to execute some code if multiple conditions are true.Syntax:if (condition) code to be executed;//condition is trueelseif (condition) code to be executed;//condition is trueelse code to be executed;//condition is falseExample:

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?

GET Method: 

  1. 1.Using get method we are able to pass 2K data from HTML.
  2. 2.All data we are passing to Server will be displayed on the Browser. 
  3. 3.This is used to sent small size data. 

POST Method:

1.In this method we does not have any size limitation. 

2.All data passed to server will be hidden, User cannot able to see this info on the browser.

3.The data is send into a small packets. This used to sent large amount of data.

What is PHP?

PHP(PHP:Hypertext Preprocessor) is a server-side programing languages.

It is use to made the web pages dynamically.

PHP is introduce by Rasmus Lerdorf in 1995.

It is a free released and open source software 

We introduce PHP under the HTML tags.

In this scripts are executed on server side.

It supports many database like that MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.

Tell more about PHP file?

In PHP file we may contain text, HTML tags and scripts.It returned to the browser in form of plain HTML code.We can save PHP file using these three extension .php,.php3 or .phtml. 

An Example of PHP file are given below:

<html>
<head><title>PHPExample</title></head>
<body>
<h1><?php echo \"Welcome in PHP world\"; ?></h1>
<?php
$txt = \"This is my first PHP script\";
/* statement */
echo $txt;
?>
</body>
</html>

How PHP is more secure than JavaScript?

It is much secure than JavaScript because of when client process the PHP page than PHP code only send the output of given request without PHP source code.So, the PHP code Can not steal by non-authorized person.

Where in the case of JavaScript It also send the source of JavaScript to the client with output.

What do you understand about MySQL?

MySQL is an open source Relational Database Management System(RDMS).

It was introduced in 23May,1995 by MySQLAB, Its an Swedish company.Now,is a subsidiary of Sun Microsystems,.

MySQL is designed in C and C++.

We can download is codes as per rules of GNU(General Public Licence). 

It fast,reliable and flexible.It works on many platforms like:Uinux,Linux and Windows.

Why do we use PHP?

Because of several main reason we use PHP. These are: 

1.PHP runs on many different platforms like that Unix,Linux and Windows etc. 

2.It codes and software are free and easy to download. 

3.It is secure because user can only aware about output doesn\'t know how that comes. 

4.It is fast,flexible and reliable. 

5.It supports many servers like: Apache,IIS etc.

How to install PHP in our system?

First you have download PHP software from: http://www.php.net/downloads.php 

Now you have to install Database Which you want to use:

Like MySQL download from:http://www.mysql.com/downloads/index.html 

Then download server on which you want to work.from:http://httpd.apache.org/download.cgi 

 After install them you will ready to work on PHP.

What is the Syntax of PHP?

Syntax:

<?php

//statements

?>

Keep one thing in mind when we write PHP code each PHP line should ends with semicolon(;).

Tell me about basic statements that we used in PHP?

PHP has two basic statements.

These are echo and print.

Example:

echo\"Hello world..!!\";

Output:

Hello world..!!

Example:

print \"Hello world\";

Output

Hello world..!! 

What are the PHP variables?

Variables are named memory location used to store values,

Like: Strings, Numbers or Array.

In PHP their is no limit to create number of variables.

All variable in PHP starts with dollar(\"$\")sign 

We assign value to the variable using \"=\" operator. 

Syntax:$variable_name = vale;Example:

What are the Limitations of Variable Naming?

Some main limitations of Variable Naming in PHP are given below:

1.In PHP their is not a fixed limit for Variable Name as compare to other programing language. 

2.First letter of PHP Variable must start with a letters,numbers or underscore \"_\". 

3.Variable Name should be a combination of Alpha-Numeric Characters or underscores(a-z,A-Z,0-9or_) 

4.Variable name must be one word.If their is more than one word in our Variable Name.Than we can distinguish them with underscore(\"_\").Like $first_name.

How to use Switch statement in PHP?

If you want to execute more than one code than we use Switch statement.

Syntax:switch (expression) 

{ case label1: code to be executed if expression = label1;

 break;

 case label2: code to be executed if expression = label2;

 break; 

 default: code to be executed if expression is different from both label1 and label2; 

}

In this One expression is execute one time.We match a particular value.If it is matched than its correspondent case will executed.When break comes executed case will stopped and command go on next case.If none of the case are executed than default case will executed.

What do you understand with array in PHP?

We create array in PHP to solved out the problem of writing same variable name many time.

In this we create a array of variable name and enter the similar variables in terms of element.

Each element in array has a unique key.Using that key we can easily access the wanted element.

Arrays are essential for 

storing, 

managing and 

operating on sets of variables effectively. 

Array are of three types: 

1.Numeric array: Numeric array is used to create an array with a unique key 

2.Associative array : is used to create an array where each unique key is associated with their value.

3.Multidimensional array : Multidimensional array is used when we declare multiple arrays in an array.


What do you understand about Numeric array, Associative array and Multidimensional array?

1. Numeric array:In this array we entered each array element with a unique key.

Example:  array ( \"vivek\", \"vineet\", \"abhi\" ) 

2.Associative array:In this array we assign array elements with unique key and their respected values.

Example: \"Patel\"=>array ( \"hariom\" ), \"Singh\"=>array ( \"saurabh\", \"ram\", \"rohan\" ) );

3.Multidimensional array:In this array we can declare array with in an array.In this multiple arrays has a automatically assign unique key.

Example: echo \"Is \" . $families[\'Agarwal\'][0] . \" belongs to the Agarwal family?\"; 

Output:Is vivek belongs to the Agarwal family?

What do you understand about looping in PHP?

Looping uses, when we want to execute some block of code for a specific time.

In PHP Looping are of Four types: 

1.while: We uses \'while\', when we want to execute a block of code till given condition is true. 

2.do..while: We uses \'do..while\', when we want to execute a block of code at least one.After that it checks the condition if it is true than block of code is execute till condition is true,Other wise stopped the execution. 

3.for: We uses \'for\', when we want to execute a block of code many times. 

4.foreach: We uses \'foreach\', when we want to execute a block of code for each element in an array.

How to use while,do..while,for and foreach loop in PHP?

1.while:Uses, we want to execute a line of code many times till specific condition is true. 

Syntax:while (condition) 

{

code will be executed;//When condition is trueExample:\";

 $m++; 

 } 

2.do..while:Uses, we want to execute a block of code at least one time. After that it checks the condition, till its correct the block of code will executed.Otherwise stopped the execution. 

Syntax: 

do{

 code will be executed; 

}while (condition);//loop execute atleast one time whenever condition is true or false 

3.for:Uses, When we want execute a block of code for some specific times. 

Syntax:for (initialize; condition; increment/decrement)

 {

 code will be executed;

 }

4.foreach:Uses, When When we want execute a block of code for each element in an array. 

Syntax:foreach (array as value)

{ code will be executed; 

}

What do you understand functions in PHP?How we create them?

Functions are one the main property in PHP.It makes PHP useful as compare to others.PHP provides more than 701 in-build functions.How to create Functions in PHP:For creating functions in PHP we have to keep in mind these steps. 

Syntax:

function <function_name>(Parameters)

{

//Function Body;

}

How to handle form in PHP?

When we handle form in PHP keep that most important thing any form element of HTML page will be automatically goes on PHP scripts via Get and Post.

Get and Post are two associative arrays used to collect information from the web page after form is submitted.

Syntax:

$_POST[];

$_GET[];

Example:

<form method=POST>

name:<input type=text name=Text1>

<input type=submit>

</form>

<?php

echo $_POST[Text1];

?>


What is form validation?What is Client Side and Server Side validation?

If programmer created a file it should be properly validate.Using form validation we can stop the processing of incorrect input.

Because when user enter a invalid input than it may be our form will processed and generated wrong input. We can validate our form on two sides. 

1.Client Side 

2.Server Side 

In Client Side we validate form using only JavaScript.

In Server Side is used for validating passwords etc.

Client Side validation is much faster than Server Side validation. 

Some general value that you have to validate when you create form. 

 1.empty values 

2.numbers only 

3.input length 

4.email address 

5.strip HTML tags

What is the difference between constants and variables in PHP?

Contants are by default global whereas variables are not. The need to be declare as global if required.

When we used $_GET and $_POST variable?

 We know that when we use $_GET variable all data_values are display on our URL.So,using this we don\'t have to send secret data (Like:password, account code).But using we can bookmarked the importpage. We use $_POST variable when we want to send data_values without display on URL.And their is no limit to send particular amount of character.Using this we can not bookmarked the page.

Why we use $_REQUEST variable?

We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable.Example: 

Syntax:

$_REQUEST[\'name\'];

Example:

<form method=POST>

name:<input type=text name=Text1>

<input type=submit>

</form>

<?php

echo $_REQUEST[Text1];

?>


Why we use Date() function in PHP and How?

 We use Data() function in PHP to display the local time and date.

Syntax:

string date( string $format[, int $timestamp ])  

Where,tim estamp is optional. Timestamp is the unix timestamp represents the number of seconds after 1st Jan,1970 at 00:00:00 GMT.

Example:

<?php

echo Date(\"d,m,y\");

echo \"<br />\";

echo Date(\"D,d,D,Y\");

echo \"<br />\";

echo \"time: \"Date(\"h,i,sa\");

?>

Output:

12,06,2015

Fri,12,Jun,2015

time: 11:12:23am

Why we used Server Side include function?

 We use Server Side Include(SSL) to create functions,footer,header or elements.For multiple reuse those on different pages.In this we uses two functions include() and require(). Both functions are same except how they handle errors.

  1. include() function
  2. require() function
  3. include() function:When error comes it show warning but not stop the execution of JavaScript.
  4. require() function:When error comes it show fatal error and also stop the execution of JavaScript.

    

How we use include() and require() function in PHP?

The main difference between include() and require() is that, In PHP if file does not exist and specified with include_once() it gives show warning message or non-fatal error. And the statements following it are still be executed.

Where as if we specified file as require_once() it giver a fatal error. And the statements following it are not executed.

How to use File Handling in PHP?

 We Done File Handling in PHP by using fopen() function. 
Example:

<html>
<body>
<?php
$file=fopen(\"R4R Welcome.doc\",\"r\");
?>
</body>
</html>

 first parameter of fopen use for which file you want to open and the second parameter use for which mode you want to perform on that file(Like:read,write,append etc).

What types of modes we use in PHP for File Handling?

 Some modes that we use in PHP are given below:

  1. r :This perform only read operation and start at the beginning of file.
  2. r+ :This perform both read and write operation and start at the beginning of file.
  3. w :This perform only write operation.we can open and create the content of file.If file is not exist creates a new file.
  4. w+ :This perform both read and write operation. we can open and create the content of file.If file is not exist creates a new file.
  5. a :We can open and append the content of file.
  6. If file is not exist creates a new file.
  7. a+ :We can open,read and append the content of file.
  8. x :This perform only write operation.Also create new files.It will show error or return False when file is already exist.
  9. x+ :This perform both read and write operation. Also create new files.It will show error or return False when file is already exist.

How we use fopen(),fclose(),feof(),fgets() and fgetc()in PHP?

fopen() function is use to open a file in a specific mode(read write etc.).

<html>
<body>
<?php
$R4R_file=fopen(\"R4R Welcome.doc\",\"r\");
?>
</body>
</html>

fclose() function is use to close the file.

<?php
$R4R_file = fopen(\"R4R Welcome.doc\",\"r\");
//block of code
fclose($R4R_file);
?>

feof() is used to confirmed that \'end-of-file\' has been achieved.

if (feof($R4R_file))
echo \"End of file\";

fgets() is used when we want to read a single line from the file.

<?php
$R4R_file = fopen(\"R4R Welcome.doc\", \"r\") ;
while(!feof($R4R_file))
  {
  echo fgets($R4R_file). \"<br />\";
  }
fclose($R4R_file);
?>

fgetc() is used when we want to read a single character from the file.

<?php
$R4R_file=fopen(\"R4R Welcome.doc\",\"r\");
while (!feof($R4R_file))
  {
  echo fgetc($R4R_file);
  }
fclose($R4R_file);
?>

What you know about Cookie?

We use cookie to authenticate the client.Cookie file is attached with the client computer browser.Every time client computer sends the requested page with their cookies.

Their is advantage in PHP.In this we can create and retrieve the cookies values. We can create the cookie using setcookie () function.

Syntax:
setcookie(Cookie_Name, Cookie_Value, expire_time, path, domain);

What operation we can perform with Cookie?Explain it?

We can create the cookie,retrieve heir value and destroy them.
Creating a cookie: Using setcookie() function we can create a cookie.
Example:

<?php
setcookie(\"client\", \"Abhi\", time()+3600);
?>
<html>
.....
.....

Retrieve cookie value: Using $_COOKIE we can retrieve the cookie value.
Example:

<?php
// Print a cookie value
echo $_COOKIE[\"client\"];
// Using them we show the all cookie values
print_r($_COOKIE);
?>

Destroy the cookie: Keep one thing in mind when you destroying cookie that its expiry date should has been gone.
Example:
<?php
// set the expiration date to one hour ago
setcookie(\"client\", \"\", time()-3600);
?>

How we Sessions in PHP?

We use session variable to store information or change setting about client session.A session variable is assign to the each client. Session has a particular working cycle like that 

  1. It create a unique id for each client
  2. Store session variable according to client unique id.
  3. Unique id stored in cookie.

What do you understand about Exception Handling in PHP?

In PHP 5 we introduce a Exception handle to handle run time exception.It is used to change the normal flow of the code execution if a specified error condition occurs.

An exception can be thrown, and caught(\"catched\") within PHP. Write code in try block,Each try must have at least one catch block. Multiple catch blocks can be used to catch different classes of exceptions.
 
I have shown some error handler methods given below:
  1. Basic use of Exceptions
  2. Creating a custom exception handler
  3. Multiple exceptions
  4. Re-throwing an exception
  5. Setting a top level exception handler

What is Filter?How we use them?

In PHP, We use Filters to validate and filter data coming from insecure sources,like : user entered data.

The main issue of introducing is that to make data filtering easier and quicker.

 Some filter function are given below:
  1. filter_has_var: Checks if variable of specified type exists
  2. filter_id: Returns the filter ID belonging to a named filter
  3. filter_input_array: Gets external variables and optionally filters them
  4. filter_input: Gets a specific external variable by name and optionally filters it
  5. filter_list :  Returns a list of all supported filters
  6. filter_var_array :Gets multiple variables and optionally filters them
  7. filter_var:  Filters a variable with a specified filter

What is the difference b/n \'action\' and \'target\' in form tag?

The main difference b/n \'action\' and \'target\' form tag.

<form action=\"target\">
<input type=\"hidden\" name=\"id\" value=\"11\" />
<input type=\"hidden\" name=\"sal\" value=\"222\" /> .....
</form>


Where ACTION is an attribute.It is used to inform that from which place data has been come.data destination could be of an E-mail address.
Example:
action=\"mailto:abc@xyz.com\";

Example:
action=\"c:/welcome.php\"; It is an CGI script.
Example:
 action=\"/cgi-sys/formmail.pl\";
page that will process the data
Example:
action=\"search.asp\",
 

What is the DDL,DCL and DML?

DDL stands for Data Definition Language,DCL stands for Data Control Language and DML stands for Data Manipulation Language.

We use DDL to Create,Alter or Drop the Data objects.
We use DCL to do control over on Database transaction.In Oracle Grant and Revoke to control the transaction.
We use DML to manipulate(Insert,Update,Delete) with the existing data in the database objects.

Write some array sort functions available in php ?

I have given you eleven functions that are available in PHP for sorting an array:
  1. asort()
  2. arsort()
  3. ksort()
  4. krsort()
  5. sort()
  6. uasort()
  7. uksort()
  8. usort()
  9. rsort()
  10. natsort()
  11. natcatsort()
 

How to encrypt the password in PHP?

I have given you some examples that are used to encrypt the password in PHP:
Example:
Using md5() we can encrypt the password.
<?php
  $password = crypt(\'ownpassword\');
  if(crypt($user_input, $password)==$password)
     {
        echo \"Password checked!\";
     }
  ?>

 Above given both method only use to encrypt the password,Not used to decrypt password.

Which pre-defined classes in php?

Pre-defined classes that are in PHP are given below:
Standard Defined Classes
1.  Directory
    The class from which dir() is instantiated.
2.  stdClass
Predefined classes as of PHP  
1.  php_user_filter
Special Classes  
1.  self  
2.  parent

What is the difference between unlink and unset ?

The basic difference between unlink and unset is that, We use unlink function for file system handling.It will simply delete the file.Where unset is used to destroy the variable.

What do you understand about PHP accelerator ?

Basically PHP accelerator is used to boost up the performance of PHP programing language.We use PHP accelerator to reduce the server load and also use to enhance the performance of PHP code near about 2-10 times.In one word we can say that PHP accelerator is code optimization technique. 

How to get path of php.ini with a PHP script?

We use phpinfo(); to get path of php.ini with a PHPScript. 

Output of the code? $objM = new M(); // Where, M is a class $objN = $objM;

Both objM and objN are store same values.Because objM get the values from new M(); and it assign to the objN.So, we can say that both have contain same values.

How to distinguish between PHP and HTML?

Some main advantages between PHP and HTML are given below: 

1. PHP is an server-side programing language where as HTML is an client-side programing language. 

2. HTML is an static language where PHP is an dynamic language.

Using PHP we can share files between webpages and accessing databases. 

But we have to still use HTML to work on PHP.

How we use ceil() and floor() function in PHP?

ceil() is use to find nearest maximum values of passing value. 

Example: 

$var=6.5; 

$ans_var=ceil($var); 

echo $ans_var; 

Output:7 

floor() is use to find nearest minimum values of passing value. 

Example: 

$var=6.5 

$ans_var=floor($var); 

echo $ans_var; 

Output:6

What is the different b/w session and cookies in php?

The main difference b/n session and cookies in php are given below:
  1. We store cookies in client machine and sessions in server machine.
  2. Sessions are secured where as cookies are unsecured.
  3. In cookies we stored limited amount of data,where as using session we can stored unlimited amount of data.
  4. Session can store objects where cookies can store only strings.
  5. Sessions work slower as compare to cookies.   

What is the difference b/w isset and empty?

The main difference b/w isset and empty are given below:
isset: This variable is used to handle functions and checked a variable is set even through it is empty.
empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.

Tell how we can run PHP in command line?

We can PHP in command line by using that:
php MyFileName.php

Can i convert PHP code into JAVA code?if yes,how?

Yes,We can convert PHP code into JAVA code.Like that:
echo ""

 We can write PHP tags inside the javaScript tag.
 

How echo()is differ than Print()in PHP?

The main difference b/w echo() and Print() are given below: 

1.echo() have support multiple arguments where as print() support only one argument. 

2.Echo() doesn\'t have any return type.Where as Print() does return in terms of 0 or 1 for each success.

So,that echo is faster than print because it does not returned any value. 

3.echo is a statement Where Print is a function.

4.echo() first evaluate the string after that give output. 

$i=6 

echo \"Value of i is $i\" 

output: Value of i is 6 

print \'Value of i is $i\'

output:Value of i is $i

How we use copy() and move() file uploading functions in PHP?

When we use copy function it copy the file from source location to destination location and keep original file to the source location.
Syntax:
copy($_FILES[\'uploadedfile\'][\'tmp_name\'], $destination_path)

 Where as when we use move function it copy the file from source location to destination location and delete original file from source location.
Syntax:
move_uploaded_file($_FILES[\'uploadedfile\'][\'tmp_name\'], $destination_path)

Tell me default session time in PHP and how can I change it?

The default session time in PHP is 14400.We can change it like that manner,
Synatx:
$session_time_Limit=\"14400\";
ini_set(session.gc_maxlifetime,$session_time_Limit);
 

Tell me how to use COM components in PHP?

We use COM component in PHP by using that manner,
Example:

<?php
$objCom = new COM(�AddNumber.math�);
$output = $objCom ->AddTwoNum(4,5);
echo $output;
?>

What do you understand about pear in PHP?

Basically PEAR is stands for PHP Extension And Repository.PEAR is a framework and distribution system using that we can make PHP component reusable.It has huge collection of different classes.We use this for advance scripting.
Example: Database,Mail,HTTP etc.

How we can increase the execution time of a PHP script?

I have given you some function using them you can increase the execution time of a PHP script.Default time for execution of a PHP script is 30 seconds.
These are,
  1. set_time_limit()//change execution time temporarily.
  2. ini_set()//change execution time temporarily.
  3. By modifying `max_execution_time\' value in PHP configuration(php.ini) file.//change execution time permanent.

In PHP can I get the browser properties?

Using get_browser function we can get the browser properties in PHP.
Example:
$browser_properties = get_browser(null, true);
print_r($browser_properties);

How function strstr and stristr both work in PHP?

Generally, Both function strstr and stristr are same except one thing stristr is a case sensitive where as strstr is an non-case sensitive.We use strstr to match the given word from string.
Syntax:
strstr(string,match word)

Example
:
<?php
$email_id = \'abc@xyz.com\';
$id_domain = strstr($email_id, \'@\');
echo $id_domain;
?>

output:@xyz.com

What do you understand about Joomala in PHP?

Joomala is an content management system who is programmed with PHP.Using this we can  modified the PHP site with their content easily. 

How can we create a database using PHP and myqsl?

I have given you a example using this you can create a database.
<?php
$con =mysql_connect(\"localhost\",\"vivek\",\"vivabh\");
if (!$con)
  {
     die(\'Could not connect: \' . mysql_error());
  }
if (mysql_query(\"CREATE DATABASE my_db\",$con))
  {
     echo \"Database has been created\";
  }
else
  {
     echo \"Error to create database: \" . mysql_error();
  }
mysql_close($con);
?>

Why is PHP-MySQL used for web Development?

We use PHP-MySQL in web development because both are

  1. Open source means 
  2. Free to use. 
  3. When MySQL work with PHP it gives result much faster than when MySQL work with Java/.Net/Jsp.

How session will work when we disable cookies of client browser?

Session is kind of cookie who is work on server side.For working of session on server side cookies should be enable on server side and also on client side browser.

But session will also work when cookies are disable on client side by using URL session passing.

Whst is the difference between include_once() and include() ?

how can we connect more than one database into webpage..

Pues no sé que poner

PHP Interview Questions and Answers