PHP INTERVIEW QUESTIONS [Updated]

अनुक्रम दिखाएँ

PHP INTERVIEW QUESTIONS ANSWERS

1 1c9UyiQ7ClMuR4Pk

PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning

PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required.

Syntax:

  1. void echo ( string $arg1 [, string $… ] )  

In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.

Example Usages:

<?php 
   $a=true ;
   $b=1;
   // Below condition returns true and prints a and b are equal
   if($a==$b){
    echo "a and b are equal";
   }else{
    echo "a and b are not equal";
   }
   //Below condition returns false and prints a and b are not equal because $a and $b are of  different data types.
   if($a===$b){
    echo "a and b are equal";
   }else{
    echo "a and b are not equal";
   }
?>  
  • PEAR means “PHP Extension and Application Repository”. It extends PHP and provides a higher level of programming for web developers.
  • GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
  • GET can handle a maximum of 2048 characters, POST has no such restrictions.
  • GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
  • Normally GET is used to retrieve data while POST to insert and update.

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.

As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages PHP session are used. PHP sessions are the simple way to store data for individual users/client against a unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data, if session id is not present on server PHP creates a new session, and generate a new session ID.

Example Usage:-

<?php 

// starting a session

session_start();

// Creating a session

$_SESSION['user_info'] = ['user_id' =>1,
'first_name' => 'Ramesh', 'last_name' => 'Kumar', 'status' => 'active']; // checking session if (isset($_SESSION['user_info'])) { echo "logged In"; } // un setting remove a value from session unset($_SESSION['user_info']['first_name']); // destroying complete session session_destroy(); ?>

In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we can set directly a value in $_SESSION Global.

Example usage:

<?php
   // Starting session
    session_start();
   // Use of session_register() is deprecated
    $username = "PhpScots";
    session_register("username");
   // Use of $_SESSION is preferred
    $_SESSION["username"] = "PhpScots";
?>

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.

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the “function re-declared” error.

The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

mysql_connect(servername,username,password);

$message stores variable data while $$message is used to store variable of variables.

$message stores fixed data whereas the data stored in $$message may be changed dynamically.

PHP constants are name or identifier that can’t be changed during execution of the script. PHP constants are defined in two ways:

  • Using define() function
  • Using const() function

$my_qry = mysql_query(“SELECT * FROM `users` WHERE `u_id`=’1′; “); 
$result = mysql_fetch_array($my_qry);
echo $result[‘First_name’];

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”);

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

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

PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed.

Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class .

Here is sample class with constructor and destructer in PHP.

<?php
class Foo {
   
    private $name;
    private $link;

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

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

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;
    }
}
?>

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

PHP single line comment is done in two ways:

  • Using // (C++ style single line comment)
  • Using # (Unix Shell style single line comment)

PHP multi line comment is done by enclosing all lines within /* */.

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

In PHP, there are three types of runtime errors, they are:

Warnings: 
These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script. 

Notices
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed. 

Fatal errors: 
These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.

For, while, do-while and for each.

The PHP count() function is used to count total elements in the array, or something an object.

The isset() function checks if the variable is defined and not null.

PHP supports 9 primitive types

4 scalar types:

  • integer
  • boolean
  • float
  • string

3 compound types:

  • array
  • object
  • callable

And 2 special types:

  • resource
  • NULL

In PHP both functions are used to find the first occurrence of substring in a string except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then FALSE will be returned.

Sample Usage:

<?php 
$email = ‘abc@xyz.com’;
$hostname = strstr($email, ‘@’);
echo $hostname;
output: @xyz.com
stristr() does the same thing in Case-insensitive manner
?>

There are three types of array in PHP:

  • Indexed array
  • Associative array
  • Multidimensional array

There are many array functions in PHP:

  • array()
  • array_change_key_case()
  • array_chunk()
  • count()
  • sort()
  • array_reverse()
  • array_search()
  • array_intersect()

There are many array functions in PHP:

  • strtolower()
  • strtoupper()
  • ucfirst()
  • lcfirst()
  • ucwords()
  • strrev()
  • strlen()

PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.

PHP file read functions are given below:

  • fread()
  • fgets()
  • fgetc()

The mail() function is used to send email in PHP.

  1. bool mail($to,$subject,$message,$header);  

These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to work with other regular functions.

preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with string, it returns true otherwise it returns false.

Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in the string and if pattern matched, ten replace that match with the specified pattern

Both 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.

Leave a Comment