Google News
logo
PHP Interview Questions
PHP is an acronym for PHP: Hypertext Preprocessor it is a widely-used open source(free).  PHP is a server-side scripting language designed primarily for web development and web applications. Originally created by Rasmus Lerdorf in 1994.
It is used to print a data in the webpage, Example: <?php echo 'Free Time Learn'; ?> , The following code print the text in the webpage.
The output is displayed directly to the browser.
PHP Variables are used for storing data such as numeric values, characters, character strings etc. All PHP variable names must be pre-fixed with a ( $). Variable names are case-sensitive they are ($var and $VAR are two different variables).

Syntax of declaring a PHP valid and invalid variable names :

$varName         // valid
$_varName       // valid
$__varname    // valid
$var_name       // valid
$varName21     // valid
$_var-Name  // invalid contains non alphanumeric character (-)
$_9Var  // invalid - underscore must be followed by a letter
$99Var   // invalid - must begin with a letter or underscore
They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.
PHP has a total of eight data types which we use to construct our variables  :

Arrays : are named and indexed collections of other values. An array stores multiple values in one single variable.

Booleans : Booleans are the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Floating - Floating point numbers ("floats", "doubles" or "real numbers") 

Integers : An integer data type is a number of -2, -1, 0, 1, 2, ... Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) 

notation, optionally preceded by a sign (- or +).

Objects : To initialize an object, you use the new statement to instantiate the object to a variable.

Resources : A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.

Doubles : are floating-point numbers, like 3.14159 or 49.1.

Strings  : A string is sequence(series) of characters. where every character is the same as a byte.

A string literal can be specified in three different ways.

single quoted : 'Hello world!'
double quoted : "Hello world!"
heredoc syntax : strings is by using heredoc syntax ("<<<").

NULL : The NULL is a special data type. NULL value represents that a variable has no value. NULL is the only possible value of type NULL.
We can include a file using "include() " or "require()" function with file path as its parameter.

Syntax : <?php include('css-files.php'); ?>
If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be  issued, but execution will continue.
A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script.  A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

PHP constant : define() 
Let's see the syntax of define() function in PHP.

define(name, value, case-insensitive)

name : specifies the constant name
value : specifies the constant value
case-insensitive : Default value is false. It means it is case sensitive by default.
A string is sequence(series) of characters. where every character is the same as a byte. i.e. used to store and manipulate text.

A string literal can be specified in three different ways.

single quoted : 'Hello world!'
double quoted : "Hello world!"
heredoc syntax : strings is by using heredoc syntax ("<<<").
htaccess files are configuration files of Apache Server that provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory.
PHP Operators are used to perform operations on variables and values. PHP Operators can be categorized in following groups :

Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
An array is a data structure that stores one or more similar type of values in a single variable.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

Indexed arrays : An array with a numeric index. Values are stored and accessed in linear fashion.

Associative array : An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.

Multidimensional array : An array containing one or more arrays and values are accessed using multiple indices.
Static websites content can't be changed after running the script. You can't change anything in the site. It is predefined.

Dynamic websites content of script can be changed at the run time. Its content is regenerated every time a user visit or reload. Google, yahoo and every search engine is the example of dynamic website.
WordPress
Joomla
Magento
Drupal etc.
CodeIgniter
Cake PHP
Laravel
Zend
Symfony
Phalcon
Yii Framework etc.
The PHP provides $_POST associative array to access all the sent information using POST method.
In order to access the data sent via the GET method, we you use $_GET array like this :
 
www.freetimelearning.com?var=value
$variable = $_GET[“var”]; this will now contain ‘value’
Constants in PHP are defined using define() directive, like define("FTLCONSTANT", 100);
javascript is a client side scripting language, so javascript can make popups and other things happens on someone’s PC. While PHP is server side scripting language so it does every stuff with the server.
The following code can be used for it, header("Location:index.php");
To send email using PHP, you use the mail() function. This mail() function accepts 5 parameters as follows (the last 2 are optional). 

<?php 
    mail($to,$subject,$message,$headers); 
?>

mcrypt_encrypt : string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ); 
Encrypts plaintext with given parameters

finally you can't send email from localhost. 
Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$clanguage= new Book;
$java = new Book;
$php = new Book;
The PHP date() function formats a timestamp to a more readable date and time.

Syntax :
<?php
   date(format,[timestamp]);
?>
PHP session supports in consists of a way to preserve certain data across subsequent accesses.

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

A PHP session is easily started by making a call to the session_start() function. This function first checks if a session is already started and if none is started  then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag.
Syntax :
setcookie(name, value, expire, path, domain, security);
These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged.   An error message with filename, line number and a message describing the error is sent to the web browser.

This tutorial contains some of the most common error checking methods in PHP.

We will show different error handling methods :

die() statements
Custom errors
Error reporting.
MD5 PHP implements the MD5 hash algorithm using the md5 function,
<?php 
$encrypted_text = md5 ($msg); 
?>
The PHP mail() function is used to sending emails in user or client.  Email messages is very common for  web applications  (or) web sites, for example : sending a welcome email when a user create a new account on your website,  newsletters, registration purpose,  feedback or comments and contact from etc. 
Syntax :
mail($to, $subject, $message, $headers, $parameters);
MySQL is a fast, easy to use relational database, it is Initial release date is 23 May 1995.  MySQL is  commonly used in PHP scripts to create powerful and dynamic server-side applications. 
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications
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”);​
PHP POST method :

This is the built in PHP super global array variable that is used to get values submitted via HTTP POST method.
The array variable can be accessed from any script in the program; it has a global scope.
This method is ideal when you do not want to display the form post values in the URL.
 
Syntax :
<?php
 $_POST['variable_name'];
?>
 
 
PHP GET method :
 
This is the built in PHP super global array variable that is used to get values submitted via HTTP GET method.
 
The array variable can be accessed from any script in the program; it has a global scope.
 
This method displays the form values in the URL.
 
Syntax :
<?php
$_GET['variable_name'];
?>
 
The isset() function checks if the particular variable is set and has a value other than NULL. The function returns Boolean – false if the variable is not set or true if the variable is set. The function can check multiple values: isset(var1, var2, var3…)
Firstly, PHP should allow file uploads; this can be done by making the directive file_uploads = On
 
You can then add the action method as 'post' with the encoding type as 'multipart/form-data'.
 
<form action="sample_upload.php"method="post"enctype="multipart/form-data">​


The myupload.php file contains code specific to the fule type to be uploaded, for example, image, document, etc., and details like target path, size, and other parameters.
 
You can then write the HTML code to upload the file you want by specifying the input type as 'file.'
A PHP parser is a software that converts source code that the computer can understand. This means whatever set of instructions we give in the form of code is converted into a machine-readable format by the parser. You can parse PHP code with PHP using the token_get_all function.
The App Engine Cron Service allows you to configure regularly scheduled tasks that operate at defined times or regular intervals. These tasks are commonly known as cron jobs. These cron jobs are automatically triggered by the App Engine Cron Service. For instance, you might use a cron job to send out an email report on a daily basis, or to update some cached data every 10 minutes, or refresh summary information once an hour.
 
A cron job makes an HTTP GET request to a URL as scheduled. The handler for that URL executes the logic when it is called. A cron job request is subject to the same limits as those for push task queues.
Path Traversal is a form of attack to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. To operate the web application file, Path Traversal makes use of the dot-dot-slash sequences.
 
The attacker can disclose the content of the file attacked using the Path Traversal outside the root directory of a web server or application. It is usually done to gain access token, secret passwords, and other sensitive information stored in the files.
 
Path Traversal is also known as Directory Traversal. It enables the attacker to exploit vulnerabilities present in the web file under attack.
The name of the output type needs to be specified in parentheses before the variable that is to be cast. Some examples are :
 
* (array) – casts to array
* (bool), (boolean) – casts to Boolean
* (double), (float), (real) – casts to float
* (int), (integer) – casts to integer
* (object) – casts to object
* (string) – casts to string
PHP constructor and destructor are special type functions that are automatically called when a PHP class object is created and destroyed.
 
Generally, Constructor is used to initializing the private variables for class and Destructors to free the resources created /used by the class.
 
Here is a sample class with a constructor and destructor in PHP.
 
<?php
class Sample {
   
    private $name;
    private $link;

    public function __construct($name) {
        $this->name = $name;
    }

    public function setLink(Sample $link){
        $this->link = $link;
    }

    public function __destruct() {
        echo 'Destroying: '. $this->name;
    }
}
?>
In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any runtime error will occur on that line, then the error handled by PHP
The default session time in PHP is 1440 seconds (24 minutes) and the Default session storage path is temporary folder/tmp on the server.
 
You can change default session time by using below code
 
<?php
 // server should keep session data 
    for AT LEAST 1 hour
    ini_set('session.gc_maxlifetime', 3600);

 // each client should remember their 
    session id for EXACTLY 1 hour
    session_set_cookie_params(3600);
?>
PHP Namespaces provide a way of grouping related classes, interfaces, functions and constants.

# define namespace and class in namespace
  namespace Modules\Admin\;
  class CityController {
}
# include the class using namesapce
  use Modules\Admin\CityController ;​
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().
In PHP Type hinting is used to specify the excepted data type of functions argument. Type hinting is introduced in PHP 5.
 
Example usage :
 
//send Email function argument $email Type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.
 
<?php
function sendEmail (Email $email)
{
  $email->send();
}
?>
There are 13 types of errors in PHP, We have listed all below
 
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 initial startup.
(installation)
E_CORE_WARNING: Warnings that occur during PHP 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.
PHP count function is used to get the length or numbers of elements in an array
 
<?php
   // initializing an array in PHP
      $array=['a','b','c'];
  // Outputs 3 
      echo count($array);
?>
Code to post JSON Data in a URL using CURL in PHP
 
$url='https://www.freetimelearning.com/get_details';
$jsonData='{"name":"phpScots",
"email":"phpscots@freetimelearning.com"
,'age':28
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);
func_get_args() function is used to get number of arguments passed in a PHP function.
 
Example :
function foo() {
   return  func_get_args();
}
echo foo(1,5,7,3);//output 4;
echo foo(a,b);//output 2;
echo foo();//output 0;
The unlink() function is used when you want to delete the files completely. The unset() Function is used when you want to make that file empty.
 
Unlink() function : The unlink() function is an inbuilt function in PHP which is used to delete a file. The filename of the file which has to be deleted is sent as a parameter and the function returns True on success and False on failure. The unlink() function in PHP accepts two-parameter.

Syntax : unlink(‘path to file’);
 
Unset() function : The Unset() function is an inbuilt function in PHP which is used to remove the content from the file by emptying it. It means that the function clears the content of a file rather deleting it. The unset() function not only clears the file content but also is used to unset a variable, thereby making it empty.

Syntax : unset($var);
Calculating days between two dates in PHP
 
<?Php 
$date1 = date('Y-m-d');
$date2 = '2017-11-21';
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>

Output : 1063
MCrypt is a file encryption function and that is delivered as Perl extension. It is the replacement of the old crypt() package and crypt(1) command of Unix. It allows developers to encrypt files or data streams without making severe changes to their code.
 
MCrypt is was deprecated in PHP 7.1 and completely removed in PHP 7.2.
PEAR stand for PHP Extension and Application Repository. PEAR provides :
 
* A structured library of code
* maintain a system for distributing code and for managing code packages
* promote a standard coding style
* provide reusable components.
You can use $_SERVER['REMOTE_ADDR'] to get IP address of user/client in PHP, But sometime it may not return the true IP address of the client at all time. Use Below code to get true IP address of user.
 
function getTrueIpAddr(){
 if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
  {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  }
    else
  {
      $ip=$_SERVER['REMOTE_ADDR'];
  }
    return $ip;
}
Traits in PHP are similar to Abstract classes that are not be instantiated on its own. Traits allow us to declare methods that are used by multiple classes in PHP. trait keyword is used to create Traits in PHP and can have concrete and abstract methods.
 
Syntax : 
<?php
  trait TraitName {
  // some code...
}
?>
PHP does not support multiple inheritances. To implement the features of multiple inheritances, the interface is used in PHP.
 
Example :
 
Here, two interfaces, Isbn and Type are declared and implemented in a class, book details to add the feature of multiple inheritances in PHP.
 
interface Isbn { 
public function setISBN($isbn);
}
interface Type{
public function setType($type); 
}
class bookDetails implements Isbn, Type {
private $isbn; 
private $type; 
public function setISBN($isbn)
{ 
$this -> isbn = $isbn; 
}
public function setType($type)
{ 
$this -> type = $type; 
}
}
It is an automated feature of PHP.
 
When it runs, it removes all session 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)
Appending the session ID in every local URL of the requested page for keeping the session information is called URL rewriting.
 
The disadvantages of these methods are, it doesn’t allow persistence between the sessions and, the user can easily copy and paste the URL and send it to another user.
60 .
The full form of PDO is PHP Data Objects.
 
It is a lightweight PHP extension that uses a 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.
imagetypes() gives the image format and types supported by the current version of GD-PHP.
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.
* Scalar type declarations
* Return type declarations
* Null coalescing operator (??)
* Spaceship operator
* Constant arrays using define()
* Anonymous classes
* Closure::call method
* Group use declaration
* Generator return expressions
* Generator delegation
* Space ship operator
It describe patterns in object-oriented programming. Where the classes have multiple functionality when sharing the common interface.
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.
 
Example For Loop :
//Loop will iterate for 5 times
for ($n = 0; $n <= 5; $n++) {
echo "The number is: $n <br>";
}
 
Example Foreach :
//Loop will iterate based on array elements 
$parts = array("HDD", "Monitor", "Mouse", "Keyboard"); 
foreach ($parts as $value) { 
 echo "$value <br>"; 
}
oth are used to make the changes to your PHP setting. These are explained below :
 
php.ini : It is a special file in PHP where you make changes to your PHP settings. It works when you run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting by editing a php.ini file or, making a new text file and save it as php.ini.
 
.htaccess : It is a special file that you can use to manage/change the behavior of your site. It works when PHP is installed as an Apache module. These changes include such as redirecting your domain’s page to https or www, directing all users to one page, etc.
It is easy and simple to execute PHP scripts from the windows command prompt. You just follow the below steps:
 
1. Open the command prompt. Click on Start button->Command Prompt.
 
2. In the Command Prompt, write the full path to the PHP executable(php.exe) which is followed by the full path of a script that you want to execute. You must add space in between each component. It means to navigate the command to your script location.
 
For example :
 
let you have placed PHP in C:\PHP, and your script is in C:\PHP\sample-php-script.php,

then your command line will be : C:\PHP\php.exe C:\PHP\sample-php-script.php

3. Press the enter key and your script will execute.
The explode() and split() functions are used in PHP to split the strings. Both are defined here:
 
Split() is used to split a string into an array using a regular expression whereas explode() is used to split the string by string using the delimiter.
 
Example of split() :
split(":", "this:is:a:split"); //returns an array that contains this, is, a, split.
 
Output : Array ([0] => this,[1] => is,[2] => a,[3] => split)
 
Example of explode() :
explode ("take", "take a explode example "); //returns an array which have value "a explode example"
 
Output : array([0] => "a explode example")
The list is similar to an array but it is not a function, instead, it is a language construct. This is used for the assignment of a list of variables in one operation. If you are using PHP 5 version, then the list values start from a rightmost parameter, and if you are using PHP 7 version, then your list starts with a left-most parameter. Code is like:

<?php
  $info = array('red', 'sign', 'danger');
  // Listing all the variables
  list($color, $symbol, $fear) = $info;
  echo "$color is $symbol of $fear”
?>​
MIME stands for Multipurpose Internet Mail Extensions is an extension of the email protocol. It supports exchanging of various data files such as audio, video, application programs, and many others on the internet. It can also handle ASCII texts and Simple Mail Transport Protocol on the internet.
getimagesize() function is used to get the size of an image in PHP. This function takes the path of file with name as an argument and returns the dimensions of an image with the file type and height/width.

Syntax:
array getimagesize( $filename, $image_info )
Heredoc and nowdoc are the methods to define the string in PHP in different ways.
 
* Heredoc process the $variable and special character while nowdoc doesn't do the same.

* Heredoc string uses double quotes " " while nowdoc string uses single quote ' '

* Parsing is done in heredoc but not in nowdoc.
Both MD5 and SHA256 are used as hashing algorithms. They take an input file and generate an output which can be of 256/128-bit size. This output represents a checksum or hash value. As, collisions are very rare between hash values, so no encryption takes place.
 
* The difference between MD5 and SHA256 is that the former takes less time to calculate than later one.
* SHA256 is difficult to handle than MD5 because of its size.
* SHA256 is less secure than MD5
* MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.

Concluding all points, it will be better to use MDA5 if you want to secure your files otherwise you can use SHA256.
To connect to some MySQL database, the mysqli_connect() function is used. It is used in the following way :
<?php 
  $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD");
   mysqli_select_db($database,"DATABASE_NAME"); 
?>
mysqli_pconnect() function is used for making a persistent 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.
 
Example :
$DBconnection = mysqli_connect("localhost","username","password","dbname");
// Check for valid connection
if (mysqli_connect_errno())
{
echo "Unable to connect with MySQL: " . mysqli_connect_error();
}
 
mysqli_pconnect() function is depreciated in the new version of PHP, but you can create a persistence connection using mysqli_connect with the prefix p.
You can use fopen() function to read or write or for doing both in PHP.
 
Example :
$file1 = fopen("myfile1.txt","r"); //Open for reading
$file2 = fopen("myfile2.txt","w"); //Open for writing
$file3 = fopen("myfile3.txt","r+"); //Open for reading and writing
in_array() function is used to search a particular value in an array.
 
Example :
$languages = array("HTML", "CSS", "ANGULAR", "C", "Java", "PHP", "VB.Net");
if (in_array("PHP", $languages)) {
echo "PHP is in the list";
}
else {
echo "php is not in the list";
}
mysqli_real_escape_string() function is used to escape special characters from the string for using a SQL statement
 
Example :
$DBconnection=mysqli_connect("localhost","username","password","dbname");
$productName = mysqli_real_escape_string($con, $_POST['proname']);
$ProductType = mysqli_real_escape_string($con, $_POST['protype']);
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 left side of the string.
rtrim() : It removes whitespaces from the right side of the string.

Exmple :
$str = " Tutorials for your help";
$val1 = trim($str);
$val2 = ltrim($str);
$val3 = rtrim($str);​
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.
<?php
   $x = 1;
   while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
  }
?>
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.
<?php
    if ($_FILES["file"]["error"] == 0)
   {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
   }
?>