PHP Interview Questions and Answers for freshers and experienced



Objective Questions for written Test
1. Which of the following functions allows you to store session data in a database?

A. session_start();

B. session_set_save_handler();

C. session_database_object();

D. You cannot store session data in a database.

PHP interview questions and answers provided by PCDS is fully compiled and tested on all environment so these questions can be used by freshers and 1 to 10 years experienced candidate as well. PCDS cover latest basic and advance PHP important questions on current version with examples for easy jobs search in IT Company. As its covered more then 2000 questions on file system, email, function, string, classes, array sorting, date format, memcached php, frameworks, ci from php4, php5 php6 to php7 with pear etc all added in PDF and docs, PCDS members canebooks pdf Download related with php and User can search by search option and also a form is given at the end of this page for those user who want more Interview questions and answer on php just need to fill the form and send us.

Top Most question: What the new feature in PHP7

PHP 7 has been Released on 12 nov 2015 with these update in php7
1. Zend Engine 3 performance improvements and 64-bit integer support on Windows
2. uniform variable syntax AST-based compilation process
3. added Closure::call()
4. bitwise shift consistency across platforms
5. (null coalesce) operator
6. Unicode codepoint escape syntax
7. return type declarations
8. and scalar type (integer, float, string and boolean) declarations.


Top most 100 PHP interview questions and answers are below

Next Page php interview questions and answers Next Page

Questions : 1 :: How can we encrypt the username and password using PHP?

The functions in this section perform encryption and decryption, and compression and...View answers

Questions : 2 :: What are the features and advantages of object-oriented programming in php?

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...View answers

Questions : 3 :: How can I prevent SQL-injection in PHP?


Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an...View answers

Questions : 4 :: What is PHP?

PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its...View answers

Questions : 5 :: What is the use of echo in php?

It is used to print a data in the webpage, Example: , The following code print the text in the webpage

Questions : 6 :: How to include a file to a php page?


We can include a file using "include() " or "require()" function with file path as its parameter.

Questions : 7 :: Whats the difference between include and require?

If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will...View answers

Questions : 8 :: require_once(), require(), include().What is difference between them?

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to...View answers

Questions : 9 :: Differences between GET and POST methods ?


We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

Questions : 10 :: How to declare an array in php?

Eg : var $arr = array('apple', 'grape', 'lemon');

Questions : 11 :: What is the use of 'print' in php?

This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list. Example print('PHP Interview questions'); print 'Job Interview...View answers

Questions : 12 :: What is use of in_array() function in php ?

in_array used to checks if a value exists in an array

Questions : 13 :: What is use of count() function in php ?

count() is used to count all elements in an array, or something in an object

Questions : 14 :: What is the difference between Session and Cookie?

The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple...View answers

Questions : 15 :: How to set cookies in PHP?

Setcookie("sample", "ram", time()+3600);

Questions : 16 :: How to Retrieve a Cookie Value?

eg : echo $_COOKIE["user"];

Questions : 17 :: How to create a session? How to set a value in session ? How to Remove data from a session?

Create session : session_start(); Set value into session : $_SESSION['USER_ID']=1; Remove data from a session : unset($_SESSION['USER_ID'];

Questions : 18 :: what types of loops exist in php?

for,while,do while and foreach (NB: You should learn its usage)

Questions : 19 :: How to create a mysql connection?

mysql_connect(servername,username,password);

Questions : 20 :: How to select a database?

mysql_select_db($db_name);

Questions : 21 :: How to execute an sql query? How to fetch its result ?

$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); $result = mysql_fetch_array($my_qry); echo $result['First_name'];

Questions : 22 :: Write a program using while loop

$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); while($result = mysql_fetch_array($my_qry)) { echo $result['First_name'.]."<br/>"; }

Questions : 23 :: How we can retrieve the data in the result set of MySQL using PHP?

1. mysql_fetch_row 2. mysql_fetch_array 3. mysql_fetch_object 4. mysql_fetch_assoc

Questions : 24 :: What is the use of explode() function ?

Syntax : array explode ( string $delimiter , string $string [, int $limit ] ); This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it...View answers

Questions : 25 :: What is the difference between explode() and split() functions?

Split function splits string into array by regular expression. Explode splits a string into array by string.

Questions : 26 :: What is the use of mysql_real_escape_string() function?

It is used to escapes special characters in a string for use in an SQL statement

Questions : 27 :: Write down the code for save an uploaded file in php.

if ($_FILES["file"]["error"] == 0) { move_uploaded_file($_FILES["file"]["tmp_name"],       "upload/" . $_FILES["file"]["name"]);...View answers

Questions : 28 :: How to create a text file in php?

$filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple testn"...View answers

Questions : 29 :: How to strip whitespace (or other characters) from the beginning and end of a string ?

The trim() function removes whitespaces or other predefined characters from both sides of a string.

Questions : 30 :: What is the use of header() function in php ?

The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before...View answers

Questions : 31 :: How to redirect a page in php?

The following code can be used for it, header("Location:index.php");

Questions : 32 :: How stop the execution of a php scrip ?

exit() function is used to stop the execution of a page

Questions : 33 :: How to set a page as a home page in a php based site ?

index.php is the default name of the home page in php based sites

Questions : 34 :: How to find the length of a string?

strlen() function used to find the length of a string

Questions : 35 :: what is the use of rand() in php?

It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for...View answers

Questions : 36 :: what is the use of isset() in php?

This function is used to determine if a variable is set and is not NULL

Questions : 37 :: What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?

mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both

Questions : 38 :: What is mean by an associative array?

Associative arrays are arrays that use string keys is called associative arrays.

Questions : 39 :: What is the importance of "method" attribute in a html form?

"method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the...View answers

Questions : 40 :: What is the importance of "action" attribute in a html form?

The action attribute determines where to send the form-data in the form submission.

Questions : 41 :: What is the use of "enctype" attribute in a html form?

The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data" when we are using a form for uploading...View answers

Questions : 42 :: How to create an array of a group of items inside an HTML form ?

We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP. For instance : <input...View answers

Questions : 43 :: Define Object-Oriented Methodology

Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy...View answers

Questions : 44 :: How do you define a constant?

Using define() directive, like define ("MYCONSTANT",150)

Questions : 45 :: How send email using php?

To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg :...View answers

Questions : 46 :: How to find current date and time?

The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local...View answers

Questions : 47 :: Difference between mysql_connect and mysql_pconnect?

There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your...View answers

Questions : 48 :: What is the use of "ksort" in php?

It is used for sort an array by key in reverse order.

Questions : 49 :: What is the difference between $var and $$var?

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

Questions : 50 :: What are the encryption techniques in PHP

MD5 PHP implements the MD5 hash algorithm using the md5 function, eg : $encrypted_text = md5 ($msg);

Questions : 51 :: What is the use of the function htmlentities?

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...View answers

Questions : 52 :: How to delete a file from the system

Unlink() deletes the given file from the file system.

Questions : 53 :: How to get the value of current session id?

session_id() function returns the session id for the current session.

Questions : 54 :: What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both. mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row...View answers

Questions : 55 :: What are the different types of errors in PHP ?

Here are three basic types of runtime errors in PHP: 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has...View answers

Questions : 56 :: what is sql injection ?

SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

Questions : 57 :: What is x+ mode in fopen() used for?

Read/Write. Creates a new file. Returns FALSE and an error if file already exists

Questions : 58 :: How to find the position of the first occurrence of a substring in a string

strpos() is used to find the position of the first occurrence of a substring in a string

Questions : 59 :: What is PEAR?

PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code...View answers

Questions : 60 :: Distinguish between urlencode and urldecode?

This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the...View answers

Questions : 61 :: What are the different errors in PHP?

In PHP, there are three types of runtime errors, they are: Warnings: These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user...View answers

Questions : 62 :: Why shouldn't I use mysql_* functions in PHP?

Officially deprecated (as of PHP 5.5. Will be removed in PHP 7.) Lacks an OO interface Doesn't support: Non-blocking, asynchronous queries Prepared statements or parameterized...View answers

Questions : 63 :: mysql_fetch_array() expects parameter 1 to be resource (or mysqli_result), boolean given

Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to...View answers

Questions : 64 :: How do you parse and process HTML/XML in PHP?

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5. It is an implementation of the W3C's Document Object Model Core Level 3, a platform- and language-neutral...View answers

Questions : 65 :: How to fix "Headers already sent" error in PHP

Some functions modifying the HTTP header are: header / header_remove session_start / session_regenerate_id setcookie / setrawcookie Output can be: Unintentional: Whitespace before...View answers

Questions : 66 :: PHP: "Notice: Undefined variable" and "Notice: Undefined index"

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with...View answers

Questions : 67 :: UTF-8 all the way through

Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly...View answers

Questions : 68 :: Reference - What does this symbol mean in PHP?

++ increment operator -- decrement operator Example Name Effect --------------------------------------------------------------------- ++$a Pre-increment Increments $a by...View answers

Questions : 69 :: Using a regular expression to validate an email address

The more sophisticated grammatical patterns in Perl, PCRE, and PHP can all manage to correctly parse RFC 5322 without a hitch. Python and C# should also be able to manage it, but they use a different...View answers

Questions : 70 :: What is the difference between client-side and server-side programming?

Your code is split into two entirely separate parts, the server side and the client side. | ----------> HTTP request...View answers

Questions : 71 :: How to get useful error messages in PHP?

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP...View answers

Questions : 72 :: Secure hash and salt for PHP passwords

Don'ts Don't limit what characters users can enter for passwords. Only idiots do this. Don't limit the length of a password. If your users want a sentence with...View answers

Questions : 73 :: Reference: all basic ways to sort arrays and data in PHP

$array = array(3,5,2,8); Applicable sort functions: sort rsort asort arsort natsort natcasesort ksort krsort The difference between those is merely whether key-value associations are...View answers

Questions : 74 :: How to pass variables and data from PHP to JavaScript?

accepted There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others. In no particular order: Use AJAX to...View answers

Questions : 75 :: Convert one date format into another in PHP

PHP 5.3 and up Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates...View answers

Questions : 76 :: How do you use bcrypt for hashing passwords in PHP?

bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent...View answers

Questions : 77 :: How can I convert ereg expressions to preg in PHP?

  The biggest change in the syntax is the addition of delimiters. ereg('^hello', $str); preg_match('/^hello/', $str); Delimiters can be pretty much anything that is not...View answers

Questions : 78 :: How to calculate the difference between two dates using PHP?

For PHP < 5.3 otherwise see jurka's answer below You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy...View answers

Questions : 79 :: When to use single quotes, double quotes, and backticks?

Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so...View answers

Questions : 80 :: What is the difference between single-quoted and double-quoted strings in PHP?

PHP strings can be specified not just in two ways, but in four ways. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be...View answers

Questions : 81 :: How should a model be structured in MVC?

The first thing that I must clear up is: the model is a layer. Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which...View answers

Questions : 82 :: Are PHP short tags acceptable to use?

They're not recommended because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts do support...View answers

Questions : 83 :: Reference: mod_rewrite, URL rewriting and "pretty links" explained

To understand what mod_rewrite does you first need to understand how a web server works. A web server responds to HTTP requests. An HTTP request at its most basic level looks like this: GET...View answers

Questions : 84 :: What's the best method for sanitizing user input with PHP?

It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called magic-quotes, that builds on this idea. It's nonsense. Forget about filtering (Or...View answers

Questions : 85 :: Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

What is "variable scope"? Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean...View answers

Questions : 86 :: How do I expire a PHP session after 30 minutes?

session.gc_maxlifetime session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start. But the...View answers

Questions : 87 :: jQuery Ajax POST example with PHP

HTML: <formid="foo"><labelfor="bar">A...View answers

Questions : 88 :: Grabbing the href attribute of an A element

$dom = new DOMDocument;$dom->loadHTML($html);foreach ($dom->getElementsByTagName('a') as $node) {    echo $dom->saveHtml($node), PHP_EOL;}

Questions : 89 :: Who is the father of PHP ?

Rasmus Lerdorf is known as the father of PHP.

Questions : 90 :: What is the difference between $name and $$name?

$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

Questions : 91 :: What are the method available in form submitting?

GET and POST

Questions : 92 :: How can we get the browser properties using PHP?

<?php echo $_SERVER[‘HTTP_USER_AGENT’].”nn”; $browser=get_browser(null,true); print_r($browser);...View answers

Questions : 93 :: How can we register the variables into a session?

<?php session_register($ur_session_var); ?>

Questions : 94 :: How many ways we can pass the variable through the navigation between the pages?

Register the variable into the session Pass the variable as a cookie Pass the variable as part of the URL

Questions : 95 :: How can we know the total number of elements of Array?

sizeof($array_var) count($array_var)

Questions : 96 :: How can we create a database using php?

mysql_create_db();

Questions : 97 :: 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("user@example.com","@") will return "@example.com". stristr()...View answers

Questions : 98 :: What are encryption functions in PHP?

CRYPT(), MD5()

Questions : 99 :: How to store the uploaded file to the final location?

move_uploaded_file( string filename, string destination)

Questions : 100 :: Explain mysql_error().

The mysql_error() message will tell us what was wrong with our query, similar to the message we would receive at the MySQL console.

Questions : 101 :: What is Constructors and Destructors?

CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any...View answers

Questions : 102 :: Explain the visibility of the property or method.

The visibility of a property or method must be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members...View answers

Questions : 103 :: What are the differences between Get and post methods.

There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method...View answers

Questions : 104 :: What are the differences between require and include?

Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error

Questions : 105 :: What is use of header() function in php ?

The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is...View answers

Questions : 106 :: List out the predefined classes in PHP?

Directory stdClass __PHP_Incomplete_Class exception php_user_filter

Questions : 107 :: What type of inheritance that PHP supports?

In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not supported. Classes are extended using the keyword...View answers

Questions : 108 :: What is the difference between explode and split?

Split function splits string into array by regular expression. Explode splits a string into array by string. For Example:explode(" and", "India and Pakistan and Srilanka");  split(" :",...View answers

Questions : 109 :: How do you pass a variable by value in PHP?

Just like in C++, put an ampersand in front of it, like $a = &$b;

Questions : 110 :: What does a special set of tags do in PHP?

 The output is displayed directly to the browser.

Questions : 111 :: How do you call a constructor for a parent class?

 parent::constructor($value)

Questions : 112 :: What's the special meaning of __sleep and __wakeup?

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

Questions : 113 :: What is the difference between PHP and JavaScript?

javascript is a client side scripting language, so javascript can make popups and other things happens on someone’s PC. While PHP is server side scripting language so it does every stuff with...View answers

Questions : 114 :: What is the difference between the functions unlink and unset?

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

Questions : 115 :: How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

Questions : 116 :: What are default session time and path?

default session time in PHP is 1440 seconds or 24 minutes Default session save path id temporary folder /tmp

Questions : 117 :: for image work which library?

we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work...View answers

Questions : 118 :: How can we get second of the current time using date function?

<?php $second = date(“s”); ?>

Questions : 119 :: What are the Formatting and Printing Strings available in PHP?

printf()-    Displays a formatted string sprintf()-Saves a formatted string in a variable fprintf()    -Prints a formatted string to a file number_format()-Formats...View answers

Questions : 120 :: How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link); $num_rows = mysql_num_rows($result); echo "$num_rows rows found";

Questions : 121 :: what is LIST function with their uses

LIST   is not really a function, but a language construct. list() is used to assign a list of variables in one operation. LIST  Assign variables as if they were an...View answers

Questions : 122 :: How to detect a mobile device using php

We can use below if condition for detect mobile devices using...View answers

Go On Top

Next Page php interview questions and answers Next Page

Download PHP eBooks PDF

Ask your interview questions on PHP


Write Your comment or Questions if you want the answers on PHP from PHP Experts

Name* :
Email Id* :
Question
Or
Comment* :