Php interview
Indoscie Technologies is Web Design and Development, SEO, PPC, Local Listing,
Adwords, E-mail Marketing, Digital Marketing service and solutions providers at a very affordable cost.
# What is PHP?
-->
PHP (Hyper text Pre Processor) is a scripting language commonly used for web applications. PHP can be easily embedded in HTML. PHP generally runs on a web server. It is available for free and can be used across a variety of servers, operating systems and platforms.
# 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.
# Who is the father of php and explain the changes in php versions?
-->
Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.
# 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.
# 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.
# 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.
# 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.
# What are the different tables present in mysql?
-->
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. InnoDB
5. ISAM
6. BDB
MyISAM is the default storage engine as of MySQL 3.23.
# 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.
# What is meant by nl2br()?
-->
Nl2br Inserts HTML line breaks before all newlines in a string string nl2br (string); For example: echo nl2br("god bless you")
will output "god bless you" to your browser.
# What are the current versions of apache, php, and mysql?
-->
PHP: php 5.3
MySQL:
MySQL 5.5
Apache: Apache 2.2
# 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.
# How can we encrypt and decrypt a data present in a mysql table using mysql?
-->
AES_ENCRYPT () and AES_DECRYPT ()
# 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);
# What are the different types of errors in php?
-->
E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP's initial startup
E_COMPILE_ERROR: Fatal
compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings
# 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.
# 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.
# What is the difference between the functions unlink and unset?
-->
Unlink() deletes the given file from the file system.
unset() makes a variable undefined.
# How can we register the variables into a session?
-->
We can use the
session_register ($ur_session_var) function.
# 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
# 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.
# 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.
# How can we take a backup of a mysql table and how can we restore it.?
-->
Create a full backup of your database: shell> mysqldump tab=/path/to/some/diropt 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";
mysql_close($link2);
# How many ways can we get the value of current session id?
-->
session_id() function returns the session id for the current session.
# How can we destroy the session, how can we unset the
variable of a session?
-->
session_destroy
session_unset
# How can we destroy the cookie?
-->
Set same the cookie in past
# 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.
# 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.
# What is the maximum length of a table name, database name, and fieldname in mysql?
-->
Database name- 64
Table name -64 Fieldname-64
# 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
# What is maximum size of a database in mysql?
-->
If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint.
The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 â€" 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal
limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
Operating System File-size Limit
Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem)
4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
# What is meant by MIME?
-->
Multipurpose Internet Mail Extensions.
WWW ability to recognise and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types.
#
What is meant by PEAR in php?
-->
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have
joined the project since then.
http://pear.php.net/manual/en/about.pear.php
# 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 and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is
returned as an array. Each result column is stored in an array offset, starting at offset 0.
# What is PHP?
-->
PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
# What is the difference between include and require?
-->
If you require a file and it cannot be found, the script will terminate with a fatal error. If you use include then you will get an error but the script will continue to execute. Therefore when the information you wish to
reference from another file is essential to the correct running of a page, use require.
# Is PHP a case sensitive programming language?
-->
PHP is a partially case sensitive programming language. We can use function names, class names in case insensitive manner.
# What is mean by LAMP?
-->
LAMP means combination of Linux, Apache, MySQL and PHP.
# How do you get the user's ip address in PHP?
-->
Using the server variable: $_SERVER['REMOTE_ADDR']
# How do you make one way encryption for your passwords in PHP?
-->
Using md5 function or sha1 function
# What is meant by PEAR in
php?
-->
Answer1: PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"
Answer2:
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution
and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.
# How can we repair a MySQL table?
-->
The syntex for repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command
will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.
# What is the difference between echo and print statement?
-->
Echo() can take multiple expressions,Print cannot take multiple expressions.
Print return true or false based on success or failure whereas echo just does what its told without letting you know whether or not it worked properly.
# 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.
##################################### PHP #########################################
PHP Interview Questions And Answers For 5 Year Experience 2020. Here in this blog post Coding compiler presenting a list of 50 PHP experience interview questions and advanced PHP interview questions for 5 years experienced developers. We hope that these senior PHP interview questions will help you to crack your next PHP job interview. All the best for your future and happy learning.
PHP Experience Interview Questions
How can we know the number of days between two given dates using PHP?
How can we repair a MySQL
table?
How can we get the properties of an image (size, type, width, height) using php image functions?
How can we take a backup of a mysql table and how can we restore it?
What is a persistent cookie and how it is different from the Temporary cookie?
How To Get the Uploaded File Information in the Receiving Script?
What is the difference between mysql_fetch_object and mysql_fetch_array?
What are the different tables present in MySQL?
How can we encrypt the username and password using PHP?
How can we send mail using JavaScript?
What is the difference between ereg_replace() and eregi_replace()?
How do I find out the number of
parameters passed into a function?
What’s the special meaning of __sleep and __wakeup?
What is the difference between the functions unlink() and unset()?
What is the difference between characters 23 and x23?
What’s the output of the ucwords function in this example?
What’s the difference between htmlentities() and htmlspecialchars()?
What are the different functions in sorting an array?
How can we know the count/number of elements of an array?
What is the maximum length of a table name, a database name, or a field name in MySQL?
Must Read PHP Interview Questions Books 2020
550 PHP INTERVIEW
QUESTIONS & ANSWERS: (Hands on tips for cracking the interview)
PHP : PHP Top Interview Questions and Answers: Face The PHP Interview with Confidence (PHP , Java, Software Development, Programming, Scripting Language)
PHP MCQs: Multiple Choice Questions and Answers (Quiz & Tests with Answer Keys)
PHP Interview Questions, Answers and Explanations: PHP Certification Review: PHP FAQ
PHP mySQL Web Programming Interview Questions, Answers, and Explanations: PHP mySQL FAQ
PHP Interview Questions You’ll Most Likely Be Asked: Volume 1 (Job Interview Questions)
PHP and MySQL Web Development
Learning PHP, MySQL & JavaScript with j Query, CSS
& HTML5
Beginning PHP6, Apache, MySQL Web Development (WROX)
PHP and MySQL Web Development
PHP Interview Questions And Answers For 5 Year Experience
1) How can we know the number of days between two given dates using PHP?
A) Simple arithmetic:
$date1 = date(‘Y-m-d’);
$date2 = ‘2006-07-01’;
$days = (strtotime() – strtotime()) / (60 * 60 * 24);
echo “Number of days since ‘2006-07-01’: $daysâ€;
2) How can we repair a MySQL table?
A) We can use REPAIR command to repair a table. The REPAIR command will repair the table
specified.
The syntex for repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.
3) How can we get the properties of an image (size, type, width, height) using php image functions?
A) 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
4) How can
we take a backup of a mysql table and how can we restore it?
A) Create a full backup of your database:
shell> mysqldump tab=/path/to/some/diropt 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â€;
mysql_close($link2);
5) What Is a Persistent Cookie and how it is different from Temporary cookie?
A) 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 cannot 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.
Read This Article: UI Developer Interview
Questions
6) How To Get the Uploaded File Information in the Receiving Script?
A) Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName][‘name’] – The Original file name on the browser system.
$_FILES[$fieldName][‘type’] – The file type determined by the browser.
$_FILES[$fieldName][‘size’]
– The Number of bytes of the file content.
$_FILES[$fieldName][‘tmp_name’] – The temporary filename of the file in which
The uploaded file was stored on the server.
$_FILES[$fieldName][‘error’] – The error code associated with this file upload.
The $fieldName is the name used in the <input name=â€fieldName†type=â€FILE,†/>
7) What is the difference between mysql_fetch_object and mysql_fetch_array?
A) MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an
array
8) 14. What are the different tables present in MySQL?
A) Total 5 types of tables we can create
MyISAM
Heap
Merge
INNO DB
ISAM
9) How can we encrypt the username and password using PHP?
A) You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Passwordâ€);
Or
You can use the MySQL PASSWORD() function to encrypt username and password.
Example: INSERT into user (password, …) VALUES (PASSWORD($passwordâ€)), …);
10) How can we send mail using
JavaScript?
A) No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using the “mailto†code.
Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=â€mailto:mailid@domain.com?subject=…â€;
return true;
}
PHP Developer Interview Questions And Answers For Experienced
PHP Interview Questions And Answers For 5 Year Experience
11) What is the difference between ereg_replace() and
eregi_replace()?
A) eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.
12) How do I find out the number of parameters passed into function?
A) func_num_args() function returns the number of parameters passed in.
Also Read: AngularJS Interview Questions
13) What’s the special meaning of __sleep and __wakeup?
A) __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
14) What is the difference between the functions unlink() and
unset()?
A) unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.
Interview Questions For PHP Developer
15) What is the difference between characters 23 and x23?
A) The first one is octal 23, the second is hex 23.
PHP Interview Questions And Answers For 5 Year Experience
16) What’s the output of the ucwords function in this example?
$formatted = ucwords(“PHP interview questions for experiencedâ€);
print
$formatted;
A) ucwords() makes every first letter of every word capital.
What will be printed is PHP Interview Questions For Experienced.
17) What’s the difference between htmlentities() and htmlspecialchars()?
A) htmlspecialchars only takes care of <, >, single quote ‘, double quote †and ampersand.
htmlentities translates all occurrences of character sequences that have different meaning in HTML.
18) What are the different functions in sorting an array?
A) Sorting functions in
PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
19) How can we know the count/number of elements of an array?
A) In two ways, we can count the number of elements of an array:
a) sizeof($array) – This function is an alias of count()
b) count($urarray) – This function returns the number of elements in an array.
20) What is the maximum length of a table name, a database name, or a field name in MySQL?
A) The maximum length of a table name, database name and field name is:
Database name: 64
characters
Table name: 64 characters
Column name: 64 characters
PHP Mysql Interview Questions And Answers For 5 Years Experience
21) How many values can the SET function of MySQL take?
A) MySQL SET function can take zero or more values, but at the maximum it can take 64 values.
22) What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?
A) DESCRIBE table_name;
23) What’s the difference between md5(), crc32() and sha1() crypto on PHP?
A) The major difference is the length of the hash
generated.
CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value.
This is important when avoiding collisions.
PHP Interview Questions And Answers For 5 Year Experience
24) How can we find the number of rows in a result set using PHP?
A) Here is how you can find the number of rows in a result set in PHP:
$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows foundâ€;
25) How many ways we can we find the current date using
MySQL?
A) We can find current date using MySQL in different ways, they are:
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
PHP Interview Quesetions And Answers For Senior Developers
26) How to read and display a HTML source from the website url?
A) $filename=â€https://codingcompiler.com/â€;
$fh=fopen(“$filenameâ€, “râ€);
while( !feof($fh) ){
$contents=htmlspecialchars(fgets($fh, 1024));
print “$contentsâ€;
}
fclose($fh);
?>
PHP Interview Questions And Answers For 5
Year Experience
27) How we used $_get and $_post variable in PHP?
A) 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.
28) Why we use $_REQUEST variable?
A) We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE
variable.
29) How we use ceil() and floor() function in PHP?
A) ceil() is use to find nearest maximum values of passing value.
Ceil Example:
$var=6.5;
$ans_var=ceil($var);
echo $ans_var;
Output: 7
floor() is use to find nearest minimum values of passing value.
Floor Example:
$var=6.5
$ans_var=floor($var);
echo $ans_var;
Output: 6
PHP Interview Questions And Answers For 5 Year Experience
30) What is the answer of following code echo 1< 2 and echo 1 >2 ?
A) Output of the given
code are given below:
echo 1<2
output: 1
echo 1>2
output: no output
PHP Programming Interview Questions And Answers For Experienced
31) What is the difference b/w isset and empty?
A) The main difference b/w isset and empty are:
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.
PHP Interview Questions And Answers For 5 Year Experience
32) What do you
understand about PHP accelerator ?
A) 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 accelertator is code optimization technique.
filetype:pdf
filetype:doc
filetype:txt
33) What is the functionality of MD5 function in PHP?
A) string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.
34) How can we know the number of days between two given dates using MySQL?
A) Use DATEDIFF()
SELECT DATEDIFF(NOW(),’2006-07-01′);
PHP Interview Questions And Answers For 5 Year Experience
35) How can we change the data type of a column of a table?
A) ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
PHP Experienced Interview Questions And
Answers
36) How can we encrypt and decrypt a data presented in a table using MySQL?
A) You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:
AES_ENCRYPT(str, key_str)
AES_DECRYPT(crypt_str, key_str)
37) How can I retrieve values from one database server and store them in other database server using PHP?
A) For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.
PHP Interview Questions And Answers For 5 Year Experience
38) What are encryption functions in PHP?
A)
CRYPT() and MD5()
39) How can we get second of the current time using date function?
A) $second = date(“sâ€);
40) How many ways we can give the output to a browser?
A) HTML output
PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser
PHP 5 Years Experience Interview Questions
41) How array_walk function works in PHP?
A) It is used to update the elements/index of an original array.
In array_walk, two parameter are required.
original array and an callback function,
with use of we update the array.
PHP Interview Questions And Answers For 5 Year Experience
42) How to get the 2nd highest salary of an employee, if two employees may have the same salary?
A) select salary from employee group by salary order by salary limit 1,1
43) How to find duplicate email records in users table?
A) SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
SELECT email FROM users GROUP BY email HAVING count(id) > 1
) u2 ON u1.email = u2.email;
44) How to set the header in CURL?
A) curl_setopt($ch, CURLOPT_HTTPHEADER,
Array(“Content-Type: text/xmlâ€));
PHP Interview Questions And Answers For 5 Year Experience
45) How to redirect https to HTTP URL and vice versa in .htaccess?
A) Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Redirect http to https
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
PHP Logical Interview Questions And Answers
46) What is the use of explode() function ?
A) This function is used
to split a string into an array. Syntax : array explode( string $delimiter , string $string [, int $limit ] );
47) What is the use of mysql_real_escape_string() function?
A) mysql_real_escape_string() function mainly used to escapes special characters in a string for use in an SQL statement
PHP Interview Questions And Answers For 5 Year Experience
48) What are Traits?
A) Traits are a mechanism that allows you to create reusable code in PHP where multiple inheritance is not supported. To create a Traits we use keyword trait.
49) Can you write source code to demonstrate
Traits?
A) Example of Traits
trait users {
function getUserType() { }
function getUserDescription() { }
function getUserDelete() { }
}
class ezcReflectionMethod extends ReflectionMethod {
use users;
}
class ezcReflectionFunction extends ReflectionFunction {
use users;
}
PHP Interview Questions And Answers For 5 Year Experience
50) How to start displaying errors in PHP application?
A) Add following code in PHP.
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’,
1);
error_reporting(E_ALL);
OR Add following code in .htacess
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
Sources: Real Time Interview Questions | PHP My Passion
Source: https://codingcompiler.com/php-interview-questions-answers-5-year-experience/
RELATED INTERVIEW QUESTIONS
PHP Interview Questions And Answers
Alteryx Interview Questions
AWS Cloud Support Interview Questions
Google Kubernetes Engine Interview Questions
AWS Devops Interview Questions
Apigee Interview
Questions
Actimize Interview Questions
Kibana Interview Questions
Nagios Interview Questions
Jenkins Interview Questions
Chef Interview Questions
Puppet Interview Questions
DB2 Interview Questions
AnthillPro Interview Questions
Angular 2 Interview Questions
Hibernate Interview Questions
ASP.NET Interview Questions
Kubernetes Interview Questions
Docker Interview Questions
CEH Interview Questions
CyberArk Interview Questions
Appian Interview Questions
Drools Interview Questions
Talend Interview Questions
Selenium Interview Questions
Ab Initio Interview Questions
AB
Testing Interview Questions
Mobile Application Testing Interview Questions
Pega Interview Questions
UI Developer Interview Questions
Given below is the list of most popular PHP interview questions which are commonly asked in the interviews.
Let's Explore!!
Q #1) What is PHP?
Answer:
PHP is one of the popular server-side scripting languages for developing a web application.
The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for creating dynamic content, communicating with a database server, handling session etc.
Q #2)
Why do we use PHP?
Answer:
There are several benefits of using PHP. First of all, it is totally free to use. So anyone can use PHP without any cost and host the site at a minimal cost.
It supports multiple databases. The most commonly used database is MySQL which is also free to use. Many PHP frameworks are used now for web development, such as CodeIgniter, CakePHP, Laravel etc.
These frameworks make the web development task much easier than before.
Q #3) Is PHP a strongly typed language?
Answer:
No. PHP is a weakly typed or loosely typed
language.
Which means PHP does not require to declare data types of the variable when you declare any variable like the other standard programming languages C# or Java. When you store any string value in a variable then the data type is the string and if you store a numeric value in that same variable then the data type is an Integer.
Sample code:
1
$var = "Hello"; //String
2
$var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer:
When the value of a variable is used as the name of the other variables then it is called variable variables. $$ is used to declare
variable variables in PHP.
Sample code:
1
$str = "PHP";
2
$$str = " Programming"; //declaring variable variables
3
echo "$str ${$str}"; //It will print "PHP programming"
4
echo "$PHP"; //It will print "Programming"
Q #5) What are the differences between echo and print?
Answer:
Both echo and print method print the output in the browser but there is a difference between these two methods.
echo does not return any value after printing the output and it works faster than the print method. print method is slower than the echo because it returns boolean
value after printing the output.
Sample code:
1
echo "PHP Developer";
2
$n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer:
You have to use PHP command in the command line to execute a PHP script. If the PHP file name is test.php then the following command is used to run the script from the command line.
php test.php
Q #7) How can you declare the array in PHP?
Answer:
You can declare three types of arrays in PHP. They are numeric, associative and multidimensional
arrays.
Sample code:
1
//Numeric Array
2
$computer = array("Dell", "Lenavo", "HP");
3
//Associative Array
4
$color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green");
5
//Multidimensional Array
6
$courses = array ( array("PHP",50), array("JQuery",15), array("AngularJS",20) );
Q #8) What are the uses of explode() and implode() functions?
Answer:
explode() function is used to split a string into an array and implode() function is used to make a string by combining the array elements.
Sample
code:
1
$text = "I like programming";
2
print_r (explode(" ",$text));
3
$strarr = array('Pen','Pencil','Eraser');
4
echo implode(" ",$strarr);
Q #9) Which function can be used to exit from the script after displaying the error message?
Answer:
You can use exit() or die() function to exit from the current script after displaying the error message.
Sample code:
1
if(!fopen('t.txt','r'))
2
exit(" Unable to open the file");
Sample
code:
1
if(!mysqli_connect('localhost','user','password'))
2
die(" Unable to connect with the database");
Q #10) Which function is used in PHP to check the data type of any variable?
Answer:
gettype() function is used to check the data type of any variable.
Sample code:
1
echo gettype(true).''; //boolean
2
echo gettype(10).''; //integer
3
echo gettype('Web Programming').''; //string
4
echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in
PHP?
Answer:
You need to change the value of the max_execution_time directive in the php.ini file for increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the value as follows,
1
max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference' in PHP?
Answer:
When the variable is passed as value then it is called pass variable by value.
Here, the main variable remains unchanged even when the passed variable changes.
Sample
code:
1
function test($n) {
2
$n=$n+10;
3
}
4
5
$m=5;
6
test($m);
7
echo $m;
When the variable is passed as a reference then it is called pass variable by reference. Here, both the main variable and the passed variable share the same memory location and & is used for reference.
So, if one variable changes then the other will also change.
Sample code:
1
function test(&$n) {
2
$n=$n+10;
3
}
4
$m=5;
5
test($m);
6
echo $m;
Q #13) Explain
type casting and type juggling.
Answer:
The way by which PHP can assign a particular data type for any variable is called typecasting. The required type of variable is mentioned in the parenthesis before the variable.
Sample code:
1
$str = "10"; // $str is now string
2
$bool = (boolean) $str; // $bool is now boolean
PHP does not support data type for variable declaration. The type of the variable is changed automatically based on the assigned value and it is called type juggling.
Sample code:
1
$val = 5; // $val is now number
2
$val =
"500" //$val is now string
Q #14) How can you make a connection with MySQL server using PHP?
Answer:
You have to provide MySQL hostname, username and password to make a connection with the MySQL server in mysqli_connect() method or declaring database object of the mysqli class.
Sample code:
1
$mysqli = mysqli_connect("localhost","username","password");
2
$mysqli = new mysqli("localhost","username","password");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer:
Many functions are available in PHP to retrieve the data from the
MySQL database.
Few functions are mentioned below:
mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative array.
Sample code:
1
// Associative or Numeric array
2
$result=mysqli_query($DBconnection,$query);
3
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
4
echo "Name is $row[0]
5
";
6
echo "Email is $row['email']
7
";
mysqli_fetch_row() – It is used to fetch the records in a numeric array.
Sample code:
1
//Numeric
array
2
$result=mysqli_query($DBconnection,$query);
3
$row=mysqli_fetch_array($result);
4
printf ("%s %s ",$row[0],$row[1]);
mysqli_fetch_assoc() – It is used to fetch the records in an associative array.
Sample code:
1
// Associative array
2
$result=mysqli_query($DBconnection,$query);
3
$row=mysqli_fetch_array($result);
4
printf ("%s %s ",$row["name"],$row["email"]);
mysqli_fetch_object() – It is used to fetch the records as an object.
Sample code:
1
//
Object
2
$result=mysqli_query($DBconnection,$query);
3
$row=mysqli_fetch_array($result);
4
printf ("%s %s ",$row->name,$row->email);
Q #16) What are the differences between mysqli_connect and mysqli_pconnect?
Answer:
mysqli_pconnect() function is used for making a persistence connection with the database that does not terminate when the script ends.
mysqli_connect() function searches any existing persistence connection first and if no persistence connection exists, then it will create a new database connection and terminate the connection at the end of the
script.
Sample code:
1
$DBconnection = mysqli_connect("localhost","username","password","dbname");
2
// Check for valid connection
3
if (mysqli_connect_errno())
4
{
5
echo "Unable to connect with MySQL: " . mysqli_connect_error();
6
}
mysqli_pconnect() function is depreciated in the new version of PHP, but you can create persistence connection using mysqli_connect with the prefix p.
Q #17) Which function is used in PHP to count the total number of rows returned by any query?
Answer:
mysqli_num_rows() function is used to count
the total number of rows returned by the query.
Sample code:
1
$mysqli = mysqli_connect("hostname","username","password","DBname");
2
$result=mysqli_query($mysqli,"select * from employees");
3
$count=mysqli_num_rows($result);
Q #18) How can you create a session in PHP?
Answer:
session_start() function is used in PHP to create a session.
Sample code:
1
session_start(); //Start session
2
$_SESSION['USERNAME']='Fahmida'; //Set a session value
3
unset($_SESSION['USERNAME']; //delete session value
Q #19) What is
the use of imagetypes() method?
Answer:
image types() function returns the list of supported images of the installed PHP version. You can use this function to check if a particular image extension is supported by PHP or not.
Sample code:
1
//Check BMP extension is supported by PHP or not
2
if (imagetypes() &IMG_BMP) {
3
echo "BMP extension Support is enabled";
4
}
Q #20) Which function you can use in PHP to open a file for reading or writing or for both?
Answer:
You can use fopen() function to read or write or for
doing both in PHP.
Sample code:
1
$file1 = fopen("myfile1.txt","r"); //Open for reading
2
$file2 = fopen("myfile2.txt","w"); //Open for writing
3
$file3 = fopen("myfile3.txt","r+"); //Open for reading and writing
Q #21) What is the difference between include() and require()?
Answer:
Both include() and require() function are used for including PHP script from one file to another file. But there is a difference between these functions.
If any error occurs at the time of including a file using include() function, then it continues the execution of the script after
showing an error message. require() function stops the execution of a script by displaying an error message if an error occurs.
Sample code:
1
if (!include(‘test.php’)) echo “Error in file inclusionâ€;
2
if (!require(‘test.php’)) echo “Error in file inclusionâ€;
Q #22) Which function is used in PHP to delete a file?
Answer:
unlink() function is used in PHP to delete any file.
Sample code:
1
unlink('filename');
Q #23) What is the use of strip_tags() method?
Answer:
strip_tags() function is used to retrieve the string from a text by omitting HTML, XML and PHP tags. This function has one mandatory parameter and one optional parameter. The optional parameter is used to accept particular tags.
Sample code:
1
//Remove all tags from the text
2
echo
strip_tags("<b>PHP</b> is a popular <em>scripting</em> language");
3
//Remove all tags excluding <b> tag
4
echo strip_tags("<b>PHP</b> is a popular <em>scripting</em> language","<b>");
Q #24) How can you send HTTP header to the client in PHP?
Answer:
header() function is used to send raw HTTP header to a client before any output is sent.
Sample code:
1
header('Location: http://www.your_domain/');
Q #25) Which functions are used to count the total number of array elements in
PHP?
Answer:
count() and sizeof() functions can be used to count the total number of array elements in PHP.
Sample code:$names=array(“Asaâ€,â€Prinkaâ€,â€Abhijeetâ€);
2
echo count($names);
3
$marks=array(95,70,87);
4
echo sizeof($marks);
Q #26) What is the difference between substr() and strstr()?
Answer:
substr() function returns a part of the string based on the starting point and length. Length parameter is optional for this function and if it is omitted then the remaining part of the string from the starting point will be
returned.
strstr() function searches the first occurrence of a string inside another string. The third parameter of this function is optional and it is used to retrieve the part of the string that appears before the first occurrence of the searching string.
Sample code:
1
echo substr("Computer Programming",9,7); //Returns “Programâ€
2
echo substr("Computer Programming",9); //Returns “Programmingâ€
Sample code:
1
echo strstr("Learning Laravel 5!","Laravel"); //Returns Laravel 5!
2
echo strstr("Learning Laravel 5!","Laravel",true); //Returns
Learning
Q #27) How can you upload a file using PHP?
Answer:
To upload a file by using PHP, you have to do the following tasks.
#1) Enable file_uploads directive
Open php.ini file and find out the file_uploads directive and make it on.
1
file_uploads = On
#2) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="upd" id="upd">
<input type="submit" value="Upload" name="upload">
</form>
#3)
Write PHP script to upload the file
1
if (move_uploaded_file($_FILES["upd"]["tmp_name"], "Uploads/")) {
2
echo "The file ". basename( $_FILES["upd"]["name"]). " is uploaded.";
3
} else {
4
echo "There is an error in uploading.";
5
}
Q #28) How can you declare a constant variable in PHP?
Answer:
define() function is used to declare a constant variable in PHP. Constant variable declares without the $ symbol.
Sample code:
1
define("PI",3.14);
Q #29) Which function is used in PHP to search a particular value in an
array?
Answer:
in_array() function is used to search a particular value in an array.
Sample code:
1
$languages = array("C#", "Java", "PHP", "VB.Net");
2
if (in_array("PHP", $languages)) {
3
echo "PHP is in the list";
4
}
5
else {
6
echo "php is not in the list";
7
}
Q #30) What is the use of $_REQUEST variable?
Answer:
The $_REQUEST variable is used to read the data from the submitted HTML form.
Sample code:
Here, the $_REQUEST variable is used to read the
submitted form field with the name ‘username’. If the form is submitted without any value, then it will print as “Name is emptyâ€, otherwise it will print the submitted value.
1
<?php
2
if (isset($_POST['submit'])) {
3
// collect value of input field
4
$name = $_REQUEST['username'];
5
if (empty($name)) {
6
echo "Name is empty";
7
} else {
8
echo $name;
9
}
10
}
11
else
12
{
13
?>
14
<form method="post" action="#">
15
Name: <input type="text"
name="username">
16
<input type="submit" name="submit">
17
</form>
18
<?php } ?>
Q #31) What is the difference between for and foreach loop in PHP?
Answer:
for loop is mainly used for iterating a pre-defined number of times and foreach loop is used for reading array elements or MySQL result set where the number of iteration can be unknown.
Sample code:
1
//Loop will iterate for 5 times
2
for ($n = 0; $n <= 5; $n++) {
3
echo "The number is: $n <br>";
4
}
Sample code:
1
//Loop
will iterate based on array elements
2
$parts = array("HDD", "Monitor", "Mouse", "Keyboard");
3
foreach ($parts as $value) {
4
echo "$value <br>";
5
}
6
</pre>
7
<span style="color: #ff6600;"><strong>Q #32) How long does a PHP session last for?</strong></span>
8
9
<strong>Answer:</strong> By default, session data will last for 24 minutes or 1440 seconds in PHP. But if you want, you can change the duration by modifying the value of <strong>gc_maxlifetime directive</strong> in php.ini
file.
10
11
To set the session time for 30 minutes, open php.ini file and set the value of <strong>gc_maxlifetime</strong> directive as follows,
12
13
<strong>gc_maxlifetime = 1800</strong>
14
15
<strong><span style="color: #ff6600;"><strong>Q #33) What is the difference between “= =†and “= = =†operators.</strong></span></strong>
16
17
<strong><strong>Answer:</strong></strong>
18
19
“= =†is called an equivalent
operator that is used to check only the equivalency of two values but not the data types.
20
21
<span style="text-decoration: underline;"><strong>Sample code:</strong></span>
22
23
10 and “10†are equivalent by values. So, if condition will be true and print “n, is equal to 10â€.
24
<pre>$n = 10;
25
if ($n == "10")
26
echo "n is equal to 10"; //This will print
27
28
else
29
echo "n is not equal to 10";
“= = =†is called strictly equivalent operator that is used to check the
equivalency of two values by comparing both data types and values.
Sample code:
10 and “10†are equal by values but are not equal by data type. One is a string and one is a number. So, if condition will be false and print “n is not equal to 10â€.
1
$n = 10;
2
if ($n === "10")
3
echo "n is equal to 10";
4
else
5
echo "n is not equal to 10"; //This will print
Q #34) Which operator is used to combine string values in PHP?
Answer:
Two or more string values can be combined by using ‘.’
operator.
Sample code:
1
$val1 = "Software ";
2
$val2 = "Testing";
3
echo $val1.$val2; // The output is “Software Testingâ€
Q #35) What is PEAR?
Answer:
The full form of PEAR is “PHP Extension and Application Repositoryâ€.
Anyone can download reusable PHP components by using this framework at a free of cost. It contains different types of packages from different developers.
Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer:
Different type of
errors can occur in PHP.
Some major error types are mentioned below:
Fatal Errors– The execution of the script stops when this error occurs.
Sample code:
In the following script, f1() function is declared but f2() function is called which is not declared. The execution of the script will stop when f2() function will call. So, “Testing Fatal Error†will not be printed.
1
function f1()
2
{ echo "function 1";
3
}
4
f2();
5
echo “Testing Fatal Errorâ€;
Parse Errors– This type of error occurs when the coder
uses a wrong syntax in the script.
Sample code:
Here, semicolon(;) is missing at the end of the first echo statement.
1
echo "This is a testing script<br/>"
2
echo "error";
Warning Errors- This type of error does not stop the execution of a script. It continues the script even after displaying the error.
Sample code:
In the following script, if the test.txt file does not exist in the current location then a warning message will display to show the error and print “Opening File†text by continuing the execution.
1
$handler =
fopen("test.txt","r");
2
echo "Opening File";
Notice Errors- This type of error shows a minor error of the script and continues the execution after displaying the error.
Here, the variable, $a is defined but $b is not defined. So, a notice of undefined variable will display for “echo $b†statement and print “Checking notice error†by continuing the script.
Sample code:
1
$a = 100;
2
echo $b;
3
echo "Checking notice error";
Q #37) Does PHP support multiple inheritances?
Answer:
PHP does not support multiple inheritances.
To implement the features of multiple inheritances, the interface is used in PHP.
Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book details to add the feature of multiple inheritances in PHP.
1
interface Isbn {
2
public function setISBN($isbn);
3
}
4
interface Type{
5
public function setType($type);
6
}
7
class bookDetails implements Isbn, Type {
8
private $isbn;
9
private $type;
10
public function setISBN($isbn)
11
{
12
$this -> isbn =
$isbn;
13
}
14
public function setType($type)
15
{
16
$this -> type = $type;
17
}
18
}
Q #38) What are the differences between session and cookie?
Answer:
The session is a global variable which is used in the server to store the session data. When a new session creates the cookie with the session id is stored on the visitor's computer. The session variable can store more data than the cookie variable.
Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE array. Session values are removed automatically when the visitor closes
the browser and cookie values are not removed automatically.
Q #39) What is the use of mysqli_real_escape_string() function?
Answer:
mysqli_real_escape_string() function is used to escape special characters from the string for using a SQL statement
Sample code:
1
$DBconnection=mysqli_connect("localhost","username","password","dbname");
2
$productName = mysqli_real_escape_string($con, $_POST['proname']);
3
$ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the
string?
Answer:
There are three functions in PHP to remove the whitespaces from the string.
trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.
Sample code:
1
$str = " Tutorials for your help";
2
$val1 = trim($str);
3
$val2 = ltrim($str);
4
$val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer:
A
cookie file that is stored permanently in the browser is called a persistence cookie. It is not secure and is mainly used for tracking a visitor for long times.
This type of cookie can be declared as follows,
setccookie ("cookie_name", "cookie_value", strtotime("+2 years");
Q #42) How can a cross-site scripting attack be prevented by PHP?
Answer:
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.
Q #43) Which PHP global variable is used for uploading a file?
Answer:
$_FILE[] array contains all the information of an
uploaded file.
The use of various indexes of this array is mentioned below:
$_FILES[$fieldName][‘name'] – Keeps the original file name.
$_FILES[$fieldName][‘type'] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size'] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name'] – Keeps the temporary file name which is used to store the file in the server.
$_FILES[$fieldName][‘error'] – Contains error code related to the error that appears during the upload.
Q #44) What is meant by public, private, protected, static and final
scopes?
Answer:
Public– Variables, classes, and methods which are declared public can be accessed from anywhere.
Private– Variables, classes and methods which are declared private can be accessed by the parent class only.
Protected– Variables, classes, and methods which are declared protected can be accessed by the parent and child classes only.
Static– The variable which is declared static can keep the value after losing the scope.
Final– This scope prevents the child class to declare the same item again.
Q #45) How can image properties be retrieved in
PHP?
Answer:
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.
Q #46) What is the difference between abstract class and interface?
Answer:
Abstract classes are used for closely related objects and interfaces are used for unrelated objects.
PHP class can implement multiple interfaces but can’t inherit multiple abstract classes.
Common behavior can be implemented in the abstract class but
not an interface.
Q #47) What is garbage collection?
Answer:
It is an automated feature of PHP.
When it runs, it removes all sessions data which are not accessed for a long time. It runs on /tmp directory which is the default session directory.
PHP directives which are used for garbage collection include:
session.gc_maxlifetime (default value, 1440)
session.gc_probability (default value, 1)
session.gc_divisor (default value, 100)
Q #48) Which library is used in PHP to do various types of Image work?
Answer:
Using GD library, various
types of image work can be done in PHP. Image work includes rotating image, cropping an image, creating image thumbnail etc.
Q #49) What is URL rewriting?
Answer:
Appending the session ID in every local URL of the requested page for keeping the session information is called URL rewriting.
The disadvantages of this methods are, it doesn't allow persistence between the sessions and, the user can easily copy and paste the URL and send to another user.
Q #50) What is PDO?
Answer:
The full form of PDO is PHP Data Objects.
It is a lightweight PHP
extension that uses consistence interface for accessing the database. Using PDO, a developer can easily switch from one database server to the other. But it does not support all the advanced features of the new MySQL server.
Conclusion
Hope, this article will increase your confidence level to face any PHP interview. Feel free to contact us and suggest missing PHP Interview questions that you face in an interview.
source: https://www.softwaretestinghelp.com/php-interview-questions/
################################## PHP ###################################################
1) What is PHP?
PHP is a web language based on
scripts that allow developers to dynamically create generated web pages.
2) What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
3) Which programming language does PHP resemble?
PHP syntax resembles Perl and C
4) What does PEAR stand for?
PEAR means "PHP Extension and Application Repository". It extends PHP and provides a higher level of programming for web developers.
5) What is the actually used PHP version?
Version 7.1 or 7.2 is the recommended version of PHP.
6) How do you execute a PHP
PHP Interview Question #11
What are the __construct() and __destruct() methods in a PHP class?
(Question provided by Agli Pançi)
All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.
Understanding these two in PHP means that the candidate knows the very basics of OOP in PHP.
PHP Interview Question #12
How we can get the number of elements in an array?
(Question provided by Agli
Pançi)
The count() function is used to return the number of elements in an array.
Understanding of arrays and array related helper functions is important for any PHP developer.
Agli Pançi Lead Developer PHP
Author Bio
Agli Pançi is the Lead Developer of Manoolia and the co-founder of Zero1 Community Albania. He is an expert in the following languages: Node.js, Linux, WordPress, and Laravel. Hire Agli Now.
hire php developers
Find top PHP developers today.
Hire senior PHP developers on CodementorX for your team.
PHP Interview Question
#13
How would you declare a function that receives one parameter name hello?
If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
(Question provided by Oscar Andrés Monroy Medina)
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
}
?>
In this question, you can evaluate if the developer knows how to declare a function and how they would manage the fact of the parameter can or cannot be on the function call. You can also evaluate if the developer knows the if syntax and how to print text(echo
function).
PHP Interview Question #14
The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?
(Question provided by Oscar Andrés Monroy Medina)
<?php
echo array_sum(explode(',',$input));
?>
The explode function is one of the most used functions in PHP, so it’s important to know if the developer knows this function. There is no unique answer to this question, but the answer must be similar to this one.
PHP Interview Question #15
Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has
only one field, an input text field named email. How would you validate whether the field is empty? Print a message "The email cannot be empty" in this case.
(Question provided by Oscar Andrés Monroy Medina)
<?php
if(empty($_POST['email'])){
echo "The email cannot be empty";
}
?>
In this question, the candidate should be evaluated on his/her knowledge about forms management and validation. There is not unique answer for this question, but it must be similar to this one.
PHP Interview Question #15
Suppose that you have to implement a class named Dragonball. This class must have an attribute named
ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?
(Question provided by Oscar Andrés Monroy Medina)
<?php
class dragonBall{
private $ballCount;
public function __construct(){
$this->ballCount=0;
}
public function iFoundaBall(){
$this->ballCount++;
if($this->ballCount===7){
echo "You can ask for your wish.";
$this->ballCount=0;
}
}
}
?>
This question will evaluate a candidate’s knowledge about OOP.
Oscar Andrés Monroy Senior PHP Developer
Author Bio
Oscar Andrés Monroy has 8 years of experience with PHP.
He is a web developer and data miner, and specializes in PHP, Git, JavaScript, HTML/CSS, SQL, jQuery, and MySQL. Hire Oscar Now.
PHP Interview Question #16
What are the 3 scope levels available in PHP and how would you define them?
(Question provided by Merlyn
Coslett)
Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class
This is important for any PHP developer to know because it shows an understanding that building applications is more than just being able to write code. One must also have an understanding about privileges and accessibility of that code. There are times protected variables or methods are extremely important, and an understanding of scope is needed to protect the integrity of the data in your application along with provide a clear
path through the code.
PHP Interview Question #17
What are getters and setters and why are they important?
(Question provided by Merlyn Coslett)
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If a setter is not being used and the developer is just declaring
the $userName variable by hand, you could end up with results as such: "kevin", "KEVIN", "KeViN", "", etc. With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter – when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.
This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end
up in a database or other storage medium. Because PHP is commonly used to build web applications, developers will run across getters and setters in more advanced environments. They are extremely powerful yet not talked about very much. It is impressive if a developer shows that he/she knows what they are and how to use them early on.
PHP Interview Question #18
What does MVC stand for and what does each component do?
(Question provided by Merlyn Coslett)
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the view. It’s responsible for interpretation of the data sent
by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.
The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.
The view is passed data by the controller and is displayed to the user.
Overall, this question is worth knowing as the MVC design pattern has been used a lot in the last few years and is a very good design pattern to
know. Even with more advanced flows that go down to repositories and entities, they still are following the same basic idea for the Controller and View. The Model is typically just split out into multiple components to handle specific tasks related to database data, business logic etc. The MVC design pattern helps draw a better understanding of what is being used, as a whole, in the industry.
Author Bio
Merlyn Coslett has over 15 years of experience developing applications and APIs using PHP. He also has had the pleasure of interviewing and hiring many Junior to Senior level developers over the last 3 years. Hire Merlyn
Now.
PHP Interview Question #19
How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?
(Question provided by Kordian Bruck)
The candidate should not output anything to the browser before using code that modifies the HTTP headers. Once the developer calls echo or any other code that clears the buffer, the developer can no longer set cookies or headers. That is also true for error messages, so if an error happens before using the header command and the INI directive display_errors is set, then that will also cause that error to
show.
PHP Interview Question #20
What are SQL Injections, how do you prevent them and what are the best practices?
(Question provided by Kordian Bruck)
SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.
To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other
ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently.
Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds rows from the database to objects in the
application.
PHP Interview Question #21
What does the following code output?
(Question provided by Kordian Bruck)
$i = 016;
echo $i / 2;
The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.
PHP Interview Question #22
Why would you use === instead of ==?
(Question provided by Kordian Bruck)
If you would want to check for a certain type, like an integer or boolean, the === will do that exactly like one would expect from a strongly typed language, while == would convert the data temporarily
and try to match both operand’s types. The identity operator (===) also performs better as a result of not having to deal with type conversion. Especially when checking variables for true/false, one should avoid using == as this would also take into account 0/1 or other similar representation.
Author Bio
Kordian Bruck is a freelance developer and consultant for over five years doing work in many areas of coding. Security and privacy in development are his fields of interest. Hire Kordian Now.
PHP Interview Question #23
What are PSRs? Choose 1 and briefly describe it.
(Question provided by Jad
Joubran)
PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.
An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-2 here.
Author Bio
Jad Joubran is the founder & CTO of eTobb.com. He is a PHP and JavaScript expert, a fullstack instructure, and an international technology conference speaker. Hire Jad Now.
PHP Interview Question #24
What PSR Standards do you follow? Why would you follow a PSR standard?
(Question provided by Shawn Mayzes)
One should folow a PSR because coding
standards often vary between developers and companies. This can cause issues when reviewing or fixing another developer’s code and finding a code structure that is different from yours. A PSR standard can help streamline the expectations of how the code should look, thus cutting down confusion and in some cases, syntax errors.
PHP Interview Question #25
Do you use Composer? If yes, what benefits have you found in it?
(Question provided by Shawn Mayzes)
Using Composer is a tool for dependency management. The candidate can declare the libraries your product relies on and Composer will manage the installation and updating of the
libraries. The benefit is a consistent way of managing the libraries depended on so less time is spent managing the libraries.
Author Bio
Shawn Mayzes has over 10 years of experience with PHP and is the CTO of Red Stamp Agency. He is also a former EA and DDB Software Engineer, and founded larachat.co, the Slack community for the PHP Framework Laravel. Hire Shawn Now.
Extra PHP Interview Questions
Special thanks to Codementor Ben Edmunds for the following extra questions:
What’s the difference between using mysql_ functions and PDO?
Describe how inheritance works with
PHP.
Do you know what the PHP-FIG is? Describe it, describe the PSRs you know.
What classes would you create to build a basic Twitter-style status system with OOP?
What frameworks are you experienced in?
What frameworks do you prefer? Why?
Thoughts/experience with unit testing?
Exercise:
Build the Twitter style status system mentioned above using PHP (it doesn’t have to run or be error-free). This should be an MVP and take less than 30 minutes.
Author Bio
Ben is the co-host of the PHP Town Hall podcast, author of
Building Secure PHP Apps, and CTO at Mindfulware. When interviewing candidates, Ben tends to ask broad questions without exact answers to gauge both existing knowledge and the way someone thinks through a problem. Hire Ben Now.
Other PHP concepts
Our PHP interview questions here aren’t all-encompassing. Here are some additional concept that PHP developers should know:
Using htmlspecialchars namespaces and short hand array styles [] ~Darren
How to optimize code & how to pass user supplied data to SQL to avoid injection. ~Marton
Conclusion
If you're looking for a PHP developer for your e-commerce
site, desktop application, or more, we hope these 25+ interview questions get you on the right track of finding a top developer for your needs. When talking about PHP, don't forget PHP frameworks like Laravel, Symfony, and others.
Need to know more about PHP and where to find PHP Developers? Check out this post: Where to Find and Hire PHP Developers.
Once you've found a developer you'll need to draw up a contract. To help you out we've written post on What Your Freelance Developer Contract Should Cover.
Good luck!
source:
https://www.codementor.io/blog/php-interview-questions-answers-du1080ext
################################### 21 Essential PHP Interview Questions #############################################
Ques1: Consider the following code:
$str1 = 'yabadabadoo';
$str2 = 'yaba';
if (strpos($str1,$str2)) {
echo """ . $str1 . "" contains "" . $str2 . """;
} else {
echo """ . $str1 . "" does not contain "" . $str2 . """;
}
The output will be:
"yabadabadoo" does not contain "yaba"
Why? How can this code be fixed to work correctly?
ANS:
The problem
here is that strpos() returns the starting position index of $str2 in $str1 (if found), otherwise it returns false. So in this example, strpos() returns 0 (which is then coerced to false when referenced in the if statement). That’s why the code doesn’t work properly.
The correct solution would be to explicitly compare the value returned by strpos() to false as follows:
$str1 = 'yabadabadoo';
$str2 = 'yaba';
if (strpos($str1,$str2) !== false) {
echo """ . $str1 . "" contains "" . $str2 . """;
} else {
echo """ . $str1 . "" does not contain "" . $str2 . """;
}
Note that we
used the !== operator, not just the != operator. If we use !=, we’ll be back to the problem that 0 is coerced to false when referenced in a boolean expression, so 0 != false will evaluate to false.
Ques-2: What will be the output of the code below and why?
$x = 5;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;
ANS:
The output will be as follows:
5
11
7
1
5
Here’s are the two key facts that explain
why:
The term $x++ says to use the current value of $x and then increment it. Similarly, the term $x-- says to use the current value of $x and then decrement it.
The increment operator (++) has higher precedence then the sum operator (+) in order of operations.
With these points in mind, we can understand that $x+++$x++ is evaluated as follows: The first reference to $x is when its value is still 5 (i.e., before it is incremented) and the second reference to $x is then when its value is 6 (i.e., before it is again incremented), so the operation is 5 + 6 which yields 11. After this operation, the value of $x is 7 since it has been incremented
twice.
Similarly, we can understand that $x---$x-- is evaluated as follows: The first reference to $x is when its value is still 7 (i.e., before it is decremented) and the second reference to $x is then when its value is 6 (i.e., before it is again decremented), so the operation is 7 - 6 which yields 1. After this operation, the value of $x is back to its original value of 5, since it has been incremented twice and then decremented twice.
Ques-3:What will be the values of $a and $b after the code below is executed? Explain your answer.
$a = '1';
$b = &$a;
$b = "2$b";
ANS:
Both $a and $b will be equal to the
string "21" after the above code is executed.
Here’s why:
The statement $b = &$a; sets $b equal to a reference to $a (as opposed to setting $b to the then-current value of $a). Thereafter, as long as $b remains a reference to $a, anything done to $a will affect $b and vice versa.
So when we subsequently execute the statement $b = "2$b", $b is set equal to the string "2" followed by the then-current value of $b (which is the same as $a) which is 1, so this results in $b being set equal to the string "21" (i.e., the concatenation of "2" and "1"). And, since $b is a reference to $a, this has the same affect on the value of $a,
so both end up equal to "21".
Ques-4: What will be the output of each of the statements below and why?
var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);
ANS:
var_dump(0123 == 123) will output bool(false) because the leading 0 in 0123 tells the PHP interpreter to treat the value as octal (rather than decimal) value, and 123 octal is equal to 83 decimal, so the values are not equal.
var_dump('0123' == 123) will output bool(true) since the string 0123 will automatically be coerced to an integer when being compared with an integer value. Interestingly, when this conversion is
performed, the leading 0 is ignored and the value is treated as a decimal (rather than octal) value, so the values are bother 123 (decimal) and are therefore equal.
var_dump('0123' === 123) outputs bool(false) since it performs a more strict comparison and does not do the automatic type coercion of the string to an integer.
Ques-5: What is the problem with the code below? What will it output? How can it be fixed?
$referenceTable = array();
$referenceTable['val1'] = array(1, 2);
$referenceTable['val2'] = 3;
$referenceTable['val3'] = array(4, 5);
$testArray = array();
$testArray =
array_merge($testArray, $referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val3']);
var_dump($testArray);
ANS:
The output will be as follows:
array(2) { [0]=> int(1) [1]=> int(2) }
NULL
NULL
You may also see two warnings generated, similar to the following:
Warning: array_merge(): Argument #2 is not an array
Warning: array_merge(): Argument #1 is not an array
The issue here is that, if either the first or second argument to
array_merge() is not an array, the return value will be NULL. For example, although one might reasonably expect that a call such as array_merge($someValidArray, NULL) would simply return $someValidArray, it instead returns NULL! (And to make matters worse, this is not documented well at all in the PHP documentation.)
As a result, the call to $testArray = array_merge($testArray, $referenceTable['val2']) evaluates to $testArray = array_merge($testArray, 3) and, since 3 is not of type array, this call to array_merge() returns NULL, which in turn ends up setting $testArray equal to NULL. Then, when we get to the next call to array_merge(), $testArray is now NULL so
array_merge() again returns NULL. (This also explains why the first warning complains about argument #2 and the second warning complains about argument #1.)
The fix for this is straightforward. If we simply typecast the second argument to an array, we will get the desired results. The corrected array_merge() calls would therefore be as follows:
$testArray = array_merge($testArray, (array)$referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, (array)$referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray,
(array)$referenceTable['val3']);
var_dump($testArray);
which will yield the following output (and no warnings):
array(2) { [0]=> int(1) [1]=> int(2) }
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) }
Ques-6:What will this code output and why?
$x = true and false;
var_dump($x);
ANS:
Surprisingly to many, the above code will output bool(true) seeming to imply that the and operator is behaving instead as an or.
The issue here is that the =
operator takes precedence over the and operator in order of operations, so the statement $x = true and false ends up being functionally equivalent to:
$x = true; // sets $x equal to true
true and false; // results in false, but has no affect on anything
This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. For example, if the above statement $x = true and false were replaced with $x = (true and false), then $x would be set to false as expected.
Ques-7:What will $x be equal to after the statement $x = 3 + "15%" +
"$25"?
ANS:
The correct answer is 18.
Here’s why:
PHP supports automatic type conversion based on the context in which a variable or value is being used.
If you perform an arithmetic operation on an expression that contains a string, that string will be interpreted as the appropriate numeric type for the purposes of evaluating the expression. So, if the string begins with one or more numeric characters, the remainder of the string (if any) will be ignored and the numeric value is interpreted as the appropriate numeric type. On the other hand, if the string begins with a non-numeric character, then it
will evaluate to zero.
With that understanding, we can see that "15%" evaluates to the numeric value 15 and "$25" evaluates to the numeric value zero, which explains why the result of the statement $x = 3 + "15%" + "$25" is 18 (i.e., 3 + 15 + 0).
Please note that as of PHP 7.2, this code produces an error.
Ques-8:After the code below is executed, what will be the value of $text and what will strlen($text) return? Explain your answer.
$text = 'John ';
$text[10] = 'Doe';
ANS:
After the above code is executed, the value of $text will be the string “John D†(i.e.,
“Johnâ€, followed by six spaces, followed by “Dâ€) and strlen($text) will return 11.
There are two things going on here.
First of all, since $text is a string, setting a single element of $text simply sets that single character to the value specified. The statement $text[10] = 'Doe' therefore sets that single character to 'D' (i.e., the first character in the string "Doe", since an element of a string can only be a single character).
Secondly, $text[10] = 'Doe' says to set the 11th character of the string (remember that indices are zero-based) to 'D'. Prior to that statement, though, the length of the string $text
("John ") was only five. Whereas compilers or interpreters in other languages might barf (with something akin to an out-of-bounds-index error) when you then attempt to set the 11th character of a five-character string, PHP instead is very “accommodating†and instead allows this and sets all intermediate characters to blanks.
Ques-9:PHP_INT_MAX is a PHP constant that corresponds to the largest supported integer value (value is based on the version of PHP being run and the platform it is running on).
Assume that var_dump(PHP_INT_MAX) will yield int(9223372036854775807).
In that case, what will be the result of
var_dump(PHP_INT_MAX + 1)? Also, what will be the result of var_dump((int)(PHP_INT_MAX + 1))?
NOTE: It’s not important to supply the exact value when answering the question, but rather to explain what will happen and why.
ANS:
The result of var_dump(PHP_INT_MAX + 1) will be displayed as a double (in the case of this specific example, it will display double(9.2233720368548E+18)). The key here is for the candidate to know that PHP handles large integers by converting them to doubles (which can store larger values).
And interestingly, the result of var_dump((int)(PHP_INT_MAX + 1)) will be displayed as a negative number (in
the case of this specific example, it will display int(-9223372036854775808)). Again, the key here is for the candidate to know that the value will be displayed as a negative number, not to know the precise value.
Ques-10:How would you sort an array of strings to their natural case-insensitive order, while maintaing their original index association?
For example, the following array:
array(
'0' => 'z1',
'1' => 'Z10',
'2' => 'z12',
'3' => 'Z2',
'4' => 'z3',
)
After sorting, should become:
array(
'0' => 'z1',
'3' => 'Z2',
'4' =>
'z3',
'1' => 'Z10',
'2' => 'z12',
)
ANS:
The trick to solving this problem is to use three special flags with the standard asort() library function:
asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)
The function asort() is a variant of the standard function sort() that preserves the index association. The three flags used above SORT_STRING, SORT_FLAG_CASE and SORT_NATURAL forces the sort function to treat the items as strings, sort in a case-insensitive way and maintain natural order respectively.
Note: Using the natcasesort() function would not be a correct answer, since it would not maintain the
original index association of the elements of the array.
Ques-11:What is PEAR in php?
ANS:
PEAR (PHP Extension and Application Repository) is a framework and repository for reusable PHP components. PEAR is a code repository containing all kinds of php code snippets and libraries.
PEAR also offers a command-line interface that can be used to automatically install packages.
Ques-12:What are the differences between echo and print in PHP?
ANS:
echo and print are largely the same in PHP. Both are used to output data to the screen.
The only differences are as
follows:
echo does not return a value whereas print does return a value of 1 (this enables print to be used in expressions).
echo can accept multiple parameters (although such usage is rare) while print can only take a single argument.
Ques-13:Consider the following code:
$x = NULL;
if ('0xFF' == 255) {
$x = (int)'0xFF';
}
What will be the value of $x after this code executes? Explain your answer.
ANS:
Perhaps surprisingly, the answer is neither NULL nor 255. Rather, the answer is that $x will equal 0
(zero).
Why?
First, let’s consider whether '0xFF' == 255 will evaluate to true or false. When a hex string is loosely compared to an integer, it is converted to an integer. Internally, PHP uses is_numeric_string to detect that the string contains a hex value and converts it to an integer (since the other operand is an integer). So in this case, ‘0xFF’ is converted to its integer equivalent which is 255. Since 255 = 255, this condition evaluates to true. (Note that this only works for hex strings, not for octal or binary strings.)
But if that’s the case, shouldn’t the statement $x = (int)'0xFF'; execute
and result in $x being set equal to 255?
Well, the statement does execute, but it results in $x being set equal to 0, not 255 (i.e., it is not set to the integer equivalent of ‘0xFF’). The reason is that the explicit type cast of the string to an integer uses convert_to_long (which works differently than the is_numeric_string function that was used in evaluating the conditional expression, as explained above). convert_to_long processes the string one character at a time from left to right and stops at the first non-numeric character that it reaches. In the case of ‘0xFF’, the first non-numeric character is ‘x’, so the only part of the
string processed is the initial ‘0’. As a result, the value returned by (int)'0xFF' is 0, so when the code completes, $x will be equal to 0.
Ques-13:What is use of the header() function in PHP?
ANS:
header() is used to redirect from one page to another: header("Location: index.php");
header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");
header() is used to send a raw HTTP header: header('Content-Type: application/json');
Ques-14:What is the difference between include_once() and require_once(), which one would you use in circumstances where you need to connect to a database, and
why?
ANS:
include_once() or include allows a file to be included, and in cases where the file is missing or has the wrong name, we receive an error message and execution will still continue regardless.
On the other hand, require_once() or require would be suitable in cases where a file needs to be included once and if it is missing or has a wrong name then we receive a fatal error and the execution of the program stops.
require_once or require is a suitable method in cases where a database connection file is involved and helps alleviate the possibility of multiple instances of the same file being included several
times.
Ques-15: How can you tell if a number is even or odd without using any condition or loop?
ANS:
$arr=array("0"=>"Even","1"=>"Odd");
$check=13;
echo "Your number is: ".$arr[$check%2];
Ques-16: What is the difference between a session and cookies?
ANS:
A session stores the value on the server and cookies store the value in the user’s browser.
Ques-17: What does the follow code echo?
$a = "PHP";
$a = $a + 1;
echo $a;
ANS:
The number
1.
Note, in PHP 7.2 this throws a warning that a non-numeric value is encountered on the line and does not do the conversion to the int, so it echoes PHP instead.
Ques-18: $str = 'drinking giving jogging å– å– passing 制图 giving è·‘æ¥ åƒ'; // Example input
Highlight all the Chinese characters in red and return the string.
ANS:
$str = 'drinking giving jogging å– å– passing 制图 giving è·‘æ¥ åƒ';
$string = explode(' ', $str);
$chi = array_filter( explode('_', preg_replace(array('/[^p{Han}?]/u', '/(s)+/'), array('_',
'$1'), $str)));
$value = array ();
foreach ($string as $s) {
if (in_array($s, $chi)) {
$value[] = ''.$s.'';
} else {
$value[] = $s;
}
}
return (implode(' ', $value));
Ques-19: Write a sample of code showing the nested ternary conditional operator in PHP.
ANS:
$number_class = $number == 0 ? 'blue' : ($number > 0 ? 'green' : 'red');
Here we are assigning
different strings to the number_class variable based on a numeric value ($number).
Ques-20: What are Traits?
ANS:
Traits are a mechanism that provides some of the reuse advantages of multiple inheritance in languages like PHP where multiple inheritance is not supported. Traits enable developers to reuse combinations of methods from different class hierarchies.
Source: https://www.toptal.com/php/interview-questions