A list of top frequently asked PHP interview questions and answers are given below.
PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for creation of dynamic web applications.It was developed by Rasmus Lerdorf also know as Father of PHP in 1994.
PHP is a loosely typed language , we didn’t have to tell PHP which kind of Datatype a Variable is. PHP automatically converts the variable to the correct datatype , depending on its value.
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.
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.
Understanding the fundamentals of the HTTP protocol is very important to have for a PHP developer, and the differences between GET and POST are an essential part of it.
Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.
Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.
It’s important that a developer knows the powerful features of the language (s)he is working on, and Trait is one of such features.
To be able to connect to a MySQL database, we must use mysqli_connect() function as follows:
<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD"); mysqli_select_db($database,"DATABASE_NAME"); ?-->
A static variable is defined within a function only the first time, and its value can be modified during function calls as follows:
<!--?php function testFunction() {{"{"}} static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction(); //1 testFunction(); //2 testFunction(); //3 ?-->
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. Hence, hashing passwords with these algorithms can create vulnerability.
The PHP-OpenSSL extension provides several cryptographic operations including generation and verification of digital signatures.
The define() directive lets us defining a constant as follows:
define ("ACONSTANT", 123);
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2
Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID']
"13" and 12 can be compared in PHP since it casts everything to the integer type.
The name of the output type has to be specified in parentheses before the variable which is to be cast as follows:
* (int), (integer) - cast to integer
* (bool), (boolean) - cast to boolean
* (float), (double), (real) - cast to float
* (string) - cast to string
* (array) - cast to array
* (object) - cast to object
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.
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
The function func_num_args() is used to give the number of parameters passed into a function.
$$var2 contains the value 10.
:: is used to access static methods that do not require object initialization.
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.
The use of the function session_start() lets us activating a session.
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
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 packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.
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 urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.
A session stores the value on the server and cookies store the value in the user’s browser.
$a = "PHP";
$a = $a + 1;
echo $a;
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.
PHP supports 9 primitive types
4 scalar types:
3 compound types:
And 2 special types:
Mbstring is an extension used in PHP to handle non-ASCII strings. Mbstring provides multibyte specific string functions that help us to deal with multibyte encodings in PHP. Multibyte character encoding schemes are used to express more than 256 characters in the regular byte-wise coding system. Mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience PHP Character Encoding Requirements.
<?php
$tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
$lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
echo ($tomorrow-$lastmonth)/86400;
?>
<?Php $date1 = date('Y-m-d'); $date2 = '2015-10-2'; $days = (strtotime($date1)-strtotime($date2))/(60*60*24); echo $days; ?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {{"{"}}
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{{"{"}}
echo "Connection failed: " . $e->getMessage();
}
?>
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB"; // Optional
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {{"{"}}
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB"; // Optional
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {{"{"}}
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as follows:
php script.php
A static variable is defined within a function only the first time, and its value can be modified during function calls as follows:
<!--?php function testFunction() {{"{"}} static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction(); //1 testFunction(); //2 testFunction(); //3 ?-->
Yes, it is possible to share a single instance of Memcache between multiple projects. Memcache is a memory store space, and you can run memcache on one or more servers. You can also configure your client to speak to a particular set of instances. So, you can run two different Memcache processes on the same host and yet they are completely independent. Unless, if you have partitioned your data, then it becomes necessary to know from which instance to get the data from or to put into.
$x = 5;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;
The output will be as follows:
5
11
7
1
5
Here’s are the two key facts that explain why:
$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.++
) 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.
$a = '1';
$b = &$a;
$b = "2$b";
The output will be as follows:
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"
.
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.
In PHP all functions starting with __ names are magical functions/methods. Magical methods always lives in a PHP class.The definition of magical function are defined by programmer itself.
Here are list of magic functions available in PHP
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() .
Include :-Include is used to include files more than once in single PHP script.You can include a file as many times you want.
Syntax:- include(“file_name.php”);
Include Once:-Include once include a file only one time in php script.Second attempt to include is ignored.
Syntax:- include_once(“file_name.php”);
Require:-Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.
Syntax:- require(“file_name.php”);
Require Once :-Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.
Syntax:- require_once(“file_name.php”);
Difference between echo and print in PHP
Use of header()
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');