Showing posts with label PHP Interviews Questions. Show all posts
Showing posts with label PHP Interviews Questions. Show all posts

Tuesday, 10 January 2017

Redis PHP Interview questions and answers

Redis php interview questions and answers

Question: What is Redis?
Redis is an advanced key-value data store and cache. It has is also referred to as a data structure server as such the keys not only contains strings, but also hashes, sets, lists.

Question: What are the advantages of using Redis?
  1. It provides high speed
  2. It has got command level Atomic Operation (tx operation)
  3. It supports a server-side locking
  4. It has got lots of client lib

Question: What are the limitations of Redis?
  1. It is single threaded
  2. It has got limited client support
  3. It is not deployed

Question: Why Redis is different as compared to other key-value stores?
  1. Redis values can contain more complex data types, with atomic operations.
  2. Redis is an in-memory but persistent on disk database.

Question: How to delete current database?
redis-cli flushdb

Question: How to remove all database?
redis-cli flushall

Question: How to check redis is running?
try {
    $redis = new Redis();
    $redis->connect('', 6379);
    echo "Redis is running.";
    echo "Server is running: " . $redis->ping();
} catch (Exception $e) {
    echo $e->getMessage();

Question: How to set value in redis?
$redis->set("name", "Set string in redis");

Question: How to get value from redis?
 echo $redis->get('name'); //Set string in redis

Question: How to set multiple values (Array) in redis?
$redis->lpush("tutorials", "PHP");
$redis->lpush("tutorials", "MySQL");
$redis->lpush("tutorials", "Redis");
$redis->lpush("tutorials", "Mongodb");
$redis->lpush("tutorials", "Mysql");

Question: How to get array data from redis?
$list = $redis->lrange("tutorials", 0 ,5);   
/*Array ( [0] => Mysql [1] => Mongodb [2] => Redis [3] => MySQL [4] => PHP [5] => Mysql ) */
Question: How to get all keys from redis?
$keyList = $redis->keys("*");
/*Array ( [0] => tutorials [1] => name ) */
Question: How to stop redis?
/etc/init.d/redis-server stop

Question: How to start redis?
/etc/init.d/redis-server start

Question: How to re-start redis?
/etc/init.d/redis-server restart

Question: How do I move a redis database from one server to another?
  1. use BGSAVE command to Save a spanshot of the database into a dump.rdb
  2. Copy this dump.rdb file into another server.

Thursday, 16 June 2016

PHP interview questions and answers for experienced candidates

PHP interview questions and answers for experienced candidates

Question: How to POST Data using CURL in PHP?
$url = "";
$postData = 'this is raw data';
try {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 
    echo $output = curl_exec($ch);
} catch (Exception $e) {
    echo $e->getMessage();die;

Question: How to re-index an array?
    1=>'web technology experts',
    3=>'web technology experts Notes',
    4=>'web technology experts Notes  php technology',    
    10=>'PHP interview questions and answers'    

$reIndexArray = array_values($arrayData);
 Array ( [0] => web technology experts [1] => web technology experts Notes [2] => web technology experts Notes php technology [3] => PHP interview questions and answers ) 

Question: How do I add 24 hours to a in php?
$currentDate ='2016-06-16 14:30:10';
$futureDate=strtotime('+1 day', strtotime($currentDate));
echo date('Y-m-d H:i:s',$futureDate); //2016-06-17 14:30:10

Question: How to declare a global variable and get them?
//Set Global value
$GLOBALS['name'] = 'Web technology experts notes';

//Get Global value
echo $GLOBALS['name'];

Question: How to get the location of php.ini?

This is let you know where is your php.ini file located.

Question: How to Serializing PHP object to JSON?
$obj=  new stdClass();
    1=>'web technology experts',
    3=>'web technology experts Notes',
    4=>'web technology experts Notes  php technology',    
    10=>'PHP interview questions and answers'    
$obj->data =$arrayData;

echo json_encode($obj);

{"data":{"1":"web technology experts","3":"web technology experts Notes","4":"web technology experts Notes php technology","10":"PHP interview questions and answers"}}

Question: How to get duplicate values from array?
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'banana', 'banana', 'orange');

    [apple] => 2
    [orange] => 2
    [pear] => 2
    [banana] => 3

Question: How to identify server IP address in PHP?

Question: How to generate PDF File in PHP? You can use third party library.

Friday, 20 May 2016

PHP Interview Questions for 3 year Experience

PHP Interview Questions for 3 year Experience

Question: How to explode a string using multiple delimiters("," and "|" )?
$string='php, interview | questions , and | answers ';
$output = preg_split( "/(\,|\|)/", $string );
print_r($output );
Array ( [0] => php [1] => interview [2] => questions [3] => and [4] => answers ) 

Question: What is Late static bindings in PHP?
Late static bindings comes in PHP 5.3.0. It is used to reference the called class in the context of static inheritance.

Question: Why cause $_FILES may be empty when uploading files to PHP?

Following reason may be for empty of $_FILES

  1. multipart/form-data is missing in form tag. <form action="vanilla-upload.php" enctype="multipart/form-data" method="POST"> </form>
  2. /tmp folder does not have enough permission. In this folder uploaded file moved temporary.
  3. You have upload heavy files more than allowd in php.ini (post_max_size and upload_max_filesize)
  4. file_uploads is off in php.ini

Question: How to convert a UNIX Timestamp to Formatted Date?
echo date("Y-m-d h:i:s A", $timestamp);//2016-05-20 05:23:54 AM

Question: How can we remove a key and value from an associative array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
Array ( [0] => one [3] => three ) 

Question: How can we remove a value from an associative array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
Array ( [0] => one [1] =>  [3] => three ) 

Question: What is meaning of ampersand(&) before the function name?
If any function start with ampersand(&), It means its call by Reference function. It will return a reference to a variable instead of the value.

Question: How to detect request is from Search Engine Bots?
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "googlebot"))
    /*This request is from search engine bots */

Question: List all files/directory in one directory?
if ($handle = opendir('D:\softwares')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry";


Question: What is mod_php?
mod_php means PHP installed as a module in Apache.

Question: How to Add 1 Day in timestamp?
$timestamp='1463721834';//2016-05-20 05:23:54 AM
//Add 1 Day
$timestamp=strtotime('+1 day', $timestamp);
echo date("Y-m-d h:i:s A", $timestamp);//2016-05-21 05:23:54 AM

Question: How to re-index an array?
$arrayData = array(0=>'one',1=>'two',3=>'three',66=>'six six',7=>'Seven'); 

$newArray = array_values($arrayData);
 * Array ( [0] => one [1] => two [3] => three [4] => six six [5] => Seven ) 

Question: How to restrict the function to be accept only array?
We can define the argument data-type, while defining the function. For Example
function testmsg(array $data) {


It will throw following error.
Catchable fatal error: Argument 1 passed to testmsg() must be of the type array, none given

Saturday, 16 January 2016

Advanced PHP Interview Questions and Answers

Advanced PHP Interview Questions and Answers

Question: What is PEAR in php?
PEAR means PHP Extension and Application Repository.
PEAR is a framework and distribution system for reusable PHP components. PEAR can be installed by bringing an automated wizard.
Following are main purpose of PEAR
A structured opensource library .
Distribution and package maintenance.
The PHP Foundation Classes (PFC)
The PHP Extension Community Library (PECL)

Question: How can we repair a MySQL table?
We can repair the MySQL with following 3 queries. Each have its own feature.
REPAIR TABLE tablename

Question: What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser.
A persistent cookie can be used for tracking long-term information.
Persistent cookies are less secure.

Question: How to create persistent cookie in php?
Cookies will only persistent for as long as you have set them.
setcookie( "cookieName", 'cookieValue', strtotime( '+1 year' ) ); //set for 1 year

Question: What is meant by urlencode and urldecode?
urlencode() returns the URL encoded version of the given string.
It convert special characters into % signs followed by two hex digits.

urldecode() returns the Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.

Question: How To Get the Uploaded File Information in PHP Global variables?
We are all data in $_FILES variable and are following
$_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.

Question: How can I execute a PHP script using command line?
php c:/wamp/www/myfile.php

Question: Are objects passed by value OR by reference?
Everything is passed by value.

Question: How do you call a constructor of a parent class from child class?

Question: Can we use include ("abc.php") two or more times?
Yes, we can include mutiple times.

Question: What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.
unset() makes a variable undefined from memory

Question: What are the different functions in sorting an array?

Question: How can we get the browser properties using PHP?

Question: How can I configure PHP to show error at runtime?

Question: How do I turn off PHP Notices?
Add following code in top of php script.

T_PAAMAYIM_NEKUDOTAYIM the scope resolution operator (double colon)

Qustion: What is output of following program?
function doSomething( &$arg )
    $return = $arg;
    $arg += 1;
    return $return;

$a = 3;
$b = doSomething( $a );

echo $a;
echo '\n';
echo $b;

Question: How to protect your website from SQL injection attack?
use mysql_real_escape_string() function.

Question: How to protect your website from CSRF (Cross-Site Request Forgery) attack?
Add a token on every important request to secure important operations

Question: How to protech your website from XSS (Cross-Site Scripting) attack?
use php function htmlentities()

Question: what is the list of sensible functions?
exec(), passthru(), system(), popen(), eval(), preg_replace() 

Question: What is output of following?
$a = 012;
echo $a / 4;

Thursday, 7 January 2016

OOP Interview Questions and Answers

OOP Interview Questions and Answers

What is Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around objects rather than actions;
Objects are instances of classes, are used to interact with one another.

Following are few examples of object-oriented programming languages
PHP, C++, Objective-C, Smalltalk, C#, Perl, Python, Ruby.

The goals of object-oriented programming are:
  1. Increased understanding.
  2. Ease of maintenance.
  3. Ease of evolution.

What is data modeling?
In class, we create multiple get/set function to get and set the data through the protected functions known as Data Modeling.
class dataModel {    
    public function __set( $key, $value ) {
        $this->$key = $value;
Following are the benefits of Data Modeling
  1. It is very fast.
  2. Smart way to  manipulation on data
  3. No extra layer of logic 
  4. Really flexible to be modeled per need 
  5. Setters can explicitly define what data can be loaded into the object

What is difference between class and interface?
1) Interfaces do not contain business logic
2)You must extend interface to use.
3) You can't create object of interface.

How Session - cookie works in PHP?
When a website open in new client machine(Browser), new sessionId is created and stored in php server and in client machine (In cookie).
All data is store in PHP Server and cookie only have sessionId. When client send sessionId with request to the server, then server fetch the data corresponsing to that sessionId and retun to the browser.

What are some of the big changes PHP has gone through in the past few years?
5.1 added PDO
5.3 - added namespace support

What is Polymorphism?
It is simply "One thing, can use in different forms"
For example, One car (class) can extend two classes (hond & Alta)

How to load classes in PHP.
We can load a class with the use of "autoload" class.
If we want to change from default function autoload to testautload function.
we can do this with "spl_autoload_register"

How to call parent constructor?

Are Parent constructors called implicitly when create an object of class?
No, Parent constructors are not called implicitly It must call this explicitly. But If Child constructors is missing then parent constructor called implicitly.

What happen, If constructor is defined as private OR protected.
If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to private BaseClass::__construct() from invalid context in. If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to protected BaseClass::__construct() from invalid context in

What happen, If New-Style constructor & old-style constructor are defined. Which one will be called.
New-Style constructor will called. But if New-Style constructor is missing, old style constructor will called.

What are different visibility of method/property?
There are 3 types of visibility of method & property and are following
Public: Can be accessed from same class method, child class and from outside of class.
Protected : Can be accessed from same class method, child class.
Private: Can be accessed from same class method only.
class TestClass
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printValue()
        echo $this->public;
        echo $this->protected;
        echo $this->private;

$obj = new TestClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal error: Cannot access protected property TestClass::$protected in
echo $obj->private; // Fatal error: Cannot access private property TestClass::$private in C:\wamp\www\arun\class\class.php on line 20
$obj->printValue(); // Shows Public, Protected and Private 

What is Scope Resolution Operator?
The Scope Resolution Operator (also called Paamayim Nekudotayim) is double colon that allows access to static, constant, and overridden properties or methods of a class. Following are different uses Access to static
Acess the constant
Access the overridden properties of parent class
Access the overridden methods of a parent class

What is Static Keyword in PHP?
  • If we declare a Method or Class Property as static, then we can access that without use of instantiation of the class.
  • Static Method are faster than Normal method.
  • $this is not available within Static Method.
  • Static properties cannot be accessed through the object(i.e arrow operator)
  • Calling non-static methods with Scope Resolution operator, generates an E_STRICT level warning.
  • Static properties may only be initialized using a literal or constant value.
  • Static properties/Normal properties Can't be initialized using expressions value.

class StaticClass
    public static $staticValue = 'foo';

    public function staticValue() {
        return self::$my_static;
echo StaticClass::$staticValue;

What is Abstraction in PHP?
  • Abstraction are defined using the keyword abstract .
  • PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated (create object).
  • To extend the Abstract class, extends operator is used.
  • You can inherit only one abstract class at one time extending.
  • Any class that contains one abstract method must also be declare as abstract. Methods defined as abstract simply declare the method's signature, they can't define the implementation.
  • All methods marked as abstract in the parent's class, declaration must be defined by the child.
  • additionally, these methods must be defined with the same (or a less restricted) visibility (Public,Protected & private).
  • Type hint & number of parameter must be match between parent & child class.

What is Interface in PHP?
  • Interfaces are defined using the interface keyword.
  • All methods declared in an interface must be public. Classes defined as Interface may not be instantiated(create object).
  • To extend the interface class, implements operator is used.
  • You can inherit number of interface class at the time of extending and number of abstract class separated by comma.
  • All methods in the interface must be implemented within a child class; failure to do so will result in a fatal error.
  • Interfaces can be extended like classes using the extends operator.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
  • Type hint & number of parameter must be match.

What is Traits in PHP?
  1. Traits are a mechanism for code reuse in single inheritance.
  2. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. 
  3. It is not possible to instantiate a Trait but addition to traditional inheritance. It is intended to reduce some limitations of single inheritance to reuse sets of methods freely in several independent classes living in different class hierarchies.
  4. Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas(,).
  5. If two Traits insert a method with the same name, a fatal error is produced.

    Example of Traits
class BaseClass{
    function getReturnType() {
        return 'BaseClass';
trait traitSample {
    function getReturnType() {
        echo "TraitSample:";

class Class1 extends BaseClass {
    use traitSample;   

$obj1 = new Class1();

What is Overloading?
It is dynamically create method / properties and performed by magic methods. Overloading method / properties are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope, Means we you are calling a function which is not exist. None of the arguments of these magic methods can be passed by reference.
In PHP, Overloading is possible

What is Object Iteration?
PHP provides a way for objects to be iterate through a list of items, for this we can use foreach. Only visible properties will be listed.
class TestClass{
    public $public='PublicVal';
    protected $protected='ProtectedVal';
    private $private='PrivateVal';
    function myfunc() {
        return 'func';
    function iterateVisible(){
        foreach($this as $key => $value) {
           print "$key => $value\n";

$obj=new TestClass();

What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final.
If the class itself is being defined final then it cannot be extended. If the function itself is being defined final then it cannot be extended.

What is Serialize function in php?
It return string containing a byte-stream representation of any value that can be stored in PHP.

Comparing Objects?
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class

What is UML?
UML stands for Unified Modeling Language.
You can do following things with UML
  • Manage project complexity.
  • create database schema.
  • Produce reports.

What are Properties of Object Oriented Systems?
  • Inheritance
  • Encapsulation of data
  • Extensibility of existing data types and classes
  • Support for complex data types
  • Aggregation
  • Association 

Question: What is serialization?
serialization: returns a string containing a byte-stream representation of any value that can be stored in PHP.
Before starting your serialization process, PHP will execute the __sleep function automatically.

What can you Serialize?
  1. Variables
  2. Arrays
  3. Objects

For example
$str_array = array( "I", "Love", "PHP" );
$serialized_str = serialize($str_array);
echo $serialized_str;

Question: What is un-serialization?
unserialize: can use this string to recreate the original variable values.
Before starting your unserialization process, PHP will execute the __wakeup function automatically.

What can you  un-Serialize?

$unserialized = unserialize('a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}');

Array ( [0] => I [1] => Love [2] => PHP )

Sunday, 15 November 2015

Top 10 PHP Interview Questions and Answers

Top 10 PHP Interview Questions and Answers

Question 1: How to redirect a page to another?
You can use header function to recirect.
header('location:"); //Redirect to home page of another website

header('location:"); //Redirect to another page and another website

header('location: php-questions-and-answers-for-experienced.html"); //Redirect to another page of same website

header('location: php-questions-and-answers-for-experienced.html?topic=php");  //Redirect to another page of same website with parameter

header('Location:', true, 301); //Permanent Redirect

Following are different use of header functions.
  1. Redirect from one page to another page. Also can redirect to another website.
  2. Help to download the file like (csv download, pdf download etc).
  3. Browser Authentication to the web page.
  4. Set the header of any page at the top of page.

Question 2: Is it secure to store a password in a session?
If you still need then please stored in encrypted form with different name (not password).

Question 3: How to set/get PHP array in cookie?
//Set an array in cookie
setcookie('no_array', $arrayData);

//Get an array from cookie
$cookie = $_COOKIE['no_array'];
$arrayData = json_decode($cookie);

Question 4: What is the difference between bindParam and bindValue?
$string='this is ';
if (strlen($string) != strlen(utf8_decode($string)))
    echo 'is unicode';
  echo 'It is Not unicode.';

Question 5: How to add 30 mins to a date?
$date = date("Y-m-d H:i:s");
date("Y/m/d h:i:s", strtotime("+30 minutes", $date));

Question 6: How to get Path From URL?
$url = "";
$path = parse_url($url);
    [scheme] => http
    [host] =>
    [path] => /2013/09/amazon-s3-introduction.html

Question 7: How to get array elements which present in two different array?
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
/**Array ( [a] => green [0] => red )*/

Question 8: How to replace array elements with another another?
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));

/*Array ( [0] => red [1] => green [2] => blue [3] => black [4] => maroon )*/

Question 9: Count number of elements in an array?
$foodArray = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

echo count($foodArray); // output 2
// recursive count
echo count($foodArray, COUNT_RECURSIVE); // output 8

Question 10: How to exchanges all keys with their associated values in an array?
$input = array("oranges", "apples","mango", "pears");
$flippedArray = array_flip($input);

/*Array ( [oranges] => 0 [apples] => 1 [mango] => 2 [pears] => 3 )*/

Saturday, 14 November 2015

PHP Questions and Answers for experienced

PHP Questions and Answers for experienced

Question: Difference between array_map, array_walk and array_filter?
array_map: This function applies the callback to the elements of the given arrays.
$arrayData= array_map('strtolower', array('One','Two','three'));
print_r($arrayData); //array ( [0] => one [1] => two [2] => three )

array_walk: This function apply a user supplied function to every member of an array
function my_function(&$item, $key){
array_walk($arrayData, 'my_function');
print_r($arrayData); //Array ( [0] => One1 [1] => Two2 [2] => three3 )

array_filter: This function filters elements of an array using a callback function.
function odd_number($item){
    return false;
    return true;
$arrayData=array_filter($arrayData, 'odd_number');
print_r($arrayData); //Array ( [0] => 1 [2] => 3 [4] => 5 )

Question: How to convert date to timestamp in PHP??
echo strtotime('2015-09-15'); //1442275200

Question: Give an easy way to encrypt/decrypt the password?
define('SALT', 'X4DSF464ADS6SC5C5D55D5'); 
function encrypt_string($text) 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 

function decrypt_string($text) 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 

echo $msg = encrypt_string("your message"); //q2s33vKz5sNPPQFzZygm4nqtjuPljaI+9q1mtcwRZ3U=
echo decrypt_string($msg);//your message

Question: How to get the last character of a string in PHP?
echo substr("web tehnology", -1); // y

Question: How to store array in constants??
define ("FRUITS", serialize($arrayData));
print_r(unserialize (FRUITS));

Question: What is the difference between bindParam and bindValue?
bindParam the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called. PDOStatement::bindValue() is not work in this way.

Question: What is use of PHP_EOL?
PHP_EOL is used to find the newline character in a cross-platform-compatible way so it handles DOS/Mac/Unix issues.

Question: How to get accurate Ip Address of client Machine?
function ip_address(){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
echo ip_address();// 

Question: How to get extension of file??
$path ='/web-tech/myimage.png';
print_r(pathinfo($path, PATHINFO_EXTENSION));

Question: How to Check if PHP session has already started?
if(session_id() == '') {
    echo "session not started";
 echo "session started";

Question: NOW() equivalent function in PHP?
echo date("Y-m-d H:i:s"); //2015-11-14 9:52:32

Question: How to get all php functions?

Friday, 13 November 2015

PHP Difficult Interview Questions and Answers

PHP Difficult Interview Questions and Answers

Question: How to check a variable is NULL OR empty string?

Also for compare you can use === to compare data type.

Question: How can I execute an anonymous function?
call_user_func(function() { echo 'anonymous function called.'; });

Question: How can I measure the speed of code written in PHP?
$startTime= microtime(true);
/** Write here you code to check **/
/** Write here you code to check **/
$endTime= microtime(true);
echo 'Time Taken to executre the code:'.$endTime-$startTime;

Question: Which PHP Extension help to debug the code?

Question: How to get Yesterday date?
date("F j, Y", strtotime( '-1 days' ) ); //November 11, 2015

Question: How to set HTTP header to UTF-8 using?
Add following at the top of page.
header('Content-Type: text/html; charset=utf-8');

Question: How to get first 20 characters from string?
echo substr('Web Technology Experts Notes',0,20);

Question: How to get last date of month of given date?
$date = "2015-11-23";
echo date("Y-m-t", strtotime($date));

Question: How do I check with PHP if file exists?
$filename = "/folder/filename.php";
if (file_exists($filename)) {    
    echo "The file $filename exists.";    
} else {
    echo "The file $filename does not exists.";

Question: How to remove non-alphanumeric characters ?
echo preg_replace("/[^A-Za-z0-9 ]/", '', 'web technology experts notes @2015 '); //web technology experts notes 2015

Question: How do I replace all line breaks (\n\r) in a string with

echo str_replace(array('\r','\n','\r\n'),'
','Hello \n Web technology');

Question: How do I format a number to a dollar amount in PHP? Give Example?
Use money_format
echo money_format('$%i', 6.6); // echos '$3.40' //echos $6.60

Question: How to prevent Browser cache for php site?
Add following code at the top of web page.
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Question: How do i get the current script file name?
echo __FILE__; //htdocs/project/index.php

Question: How to add key/value in existing array?
$arrayname['keyname'] = 'new value';

Monday, 7 September 2015

How to Detect Request type in PHP

How to Detect Request type (GET OR Post ) in PHP

Question:How to Detect Request type (Get OR Post) in PHP?
try {
    switch ($method) {
        case 'GET':
            /** Add your code here **/
            /** Add your code here **/
        case 'POST':
            /** Add your code here **/
            /** Add your code here **/
        case 'PUT':
            /** Add your code here **/
            /** Add your code here **/
        case 'HEAD':
            /** Add your code here **/
            /** Add your code here **/
        case 'DELETE':
            /** Add your code here **/
            /** Add your code here **/
        case 'OPTIONS':
            /** Add your code here **/
            /** Add your code here **/
            echo "$method method not defined";
} catch (Exception $e) {
    echo $e->getMessage();

Question: How to get all post data in PHP?
$postData = array();
    $postData = $_POST;
print_r($postData );

Question: How to get all GET data in PHP?
$getData = array();
    $getData = $_GET;
print_r($getData );

Question: How to get Document root path in PHP?

Question: How to get Client Ip-Address in PHP?

Tuesday, 30 June 2015

PHP Basic questions and answers for fresher and experienced

Top 25 PHP-Interview Questions and Answers

Question: How JSON.parse Works? Give few examples?
JSON.parse is method which is used parses a string as JSON. How to parse the string as JSON
JSON.parse('{}');              // {}
JSON.parse('null');            // null
JSON.parse('true');            // true
JSON.parse('"string"');           // "string"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]

Question: How to get the Data of any Public URL(HTML Contents)? Get the data of public URL is known as scrapping. You can use following method to get the data of public URL
  1. use file_get_contents function
  2. use CURL

Question: What is use of nl2br?
nl2br is used to insert the line break.

Question: What is .htaccess?
htaccess is configuration file for Apache Server which helps us to configure at base level configuration as well as directory level.

Question: How to get the URL of Referrer page?

Question: How to extract seconds, minutes and hour from date?
$dateTime = strtotime("2015-06-30 12:25:60");
echo date('s',$dateTime); //seconds
echo date('i',$dateTime); //Minutes
echo date('h',$dateTime); //hour in 0-12 format
echo date('H',$dateTime); //hour in 0-24 format

Question: How to get current date and time?
echo date('Y-m-d H:i:s');

Question: How to change the timezone using PHP?
echo date_default_timezone_get(); //Default time zone

date_default_timezone_set('America/Los_Angeles'); //Chnage timezone to Los_Angeles

Question: Difference between unset and unlink?
unset is used to remove the variable from scope.
unlink is used to remove the file from server.

Question: How to increase max execution time?
Following are different ways to increase the execution time?
Change dynamically with PHPv
ini_set('max_execution_time', 300);

With htaccess
php_value max_execution_time 300

Change in php.ini (NEED server restart)
max_execution_time = 120

Question: How to check a variable have number OR String value?
$testvariable ='10';
    echo "This is Number";
    echo "This is string";

Question: What is PEAR in php?
Full form of PEAR is PHP Extension and Application Repository. It is a framework and repository for reusable PHP components.

Question: What is MIME?
Full form of MIME is Multi-purpose Internet Mail Extensions.
It is standard way to get the file type of an file.

Question: Can we change the value of constant variable?
No, we can't do this.

Question: How do we destroy a session?

Question: What is a PDO classes?
PDO is an PHP extension which provides an interface to connect the database like mysql, mysqli, SQL etc.

Question: What is full form of Ajax? What is Ajax?
Full form of AJAX is Asynchronous JavaScript and XML.
Ajax is technique which is used to update the website contents without refreshing the page. Ajax get the contents from server.

Question: How to set and destroy the cookie?
setcookie("cookieName", "cookie value", time()+3600);  //Set the cookie
setcookie("cookieName", "cookie value", time()-3600);  //distroy the cookie

Question: Does PHP support multiple inheritances in PHP?
No, PHP Support only single level of inheritance.

Question: Can we achieve multiple inheritance in PHP?
PHP Does not support multiple inheritance but we can achieve multilevel inheritance in directly.
See Example below:
class a{}
class b extends a{}
class c extends b{}
class d extends c{}
class e extends d{}
class f extends e{}

As PHP Does not support multi level inheritance but we can extend mulitple classes one by one (As in Above).