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

Sunday, 5 April 2020

Laravel interview questions for 4 year experienced

Laravel interview questions for 4 year experienced

Question: What is Server Requirements for Laravel 5.6?
  1. PHP >= 7.1.3
  2. PDO PHP Extension
  3. Ctype PHP Extension
  4. OpenSSL PHP Extension
  5. XML PHP Extension
  6. JSON PHP Extension
  7. Mbstring PHP Extension
  8. Tokenizer PHP Extension

Question: What is Laravel Dusk?
It is expressive, easy-to-use browser automation and testing API.


Question: What is Laravel Echo?
Event broadcasting, evolved. Bring the power of WebSockets to your application without the complexity.


Question: How to Install Laravel via Composer?
composer create-project --prefer-dist laravel/laravel myproject



Question: How to Install any Specific version of Laravel via Composer
composer create-project --prefer-dist laravel/laravel blog "5.4.*" //Install Laravel 5.4 using Composer



Question: What is Lumen?
  1. Lumen is a micro-framework provided by Laravel.
  2. It is developed by creator of Laravel Taylor Otwell.
  3. It is mostly used for creating RESTful API's & microservices.
  4. Lumen is built on top components of Laravel.



Question: How to Install Lumen via Composer?
composer create-project --prefer-dist laravel/lumen myproject



Question: List benefits of using Laravel over other PHP frameworks?
  1. Artisan
  2. Migrations & Seeding
  3. Blade Template Engine
  4. Middleware - HTTP middleware provide a convenient mechanism for filtering HTTP requests
  5. Routing (RESTful routing)
  6. Authentication, Cashier, Scheduler, SSH, Socialite
  7. Security
  8. Unit Testing
  9. Caching


Question: Which Template Engine used by Laravel?
Blade is the simple, yet powerful templating engine provided with Laravel.


Question: How to enable maintenance mode in Laravel?
// Enable maintenance mode
php artisan down

// Disable maintenance mode
php artisan up



Question: What are Closures in Laravel?
A Closure is an anonymous function. Closures are often used as a callback methods and can be used as a parameter in a function.


Question: List out databases that laravel supports?
MySQL
PostgreSQL
SQLite
SQL Server


Question: How To Use Insert Query In Laravel?
class UserController extends Controller
{
    /**
     * Create a new user instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $user = new User;
        $user->name = $request->name;
        $user->role = $request->role;
        $user->save();
    }



Question: What are the available Router Methods?
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);



Question: How To Use Update Query In Laravel?
$result = User::where('id',1)->update(['name'=>'My web technology experts notes']);



Question: How To Use Delete Query In Laravel?
$result = User::where('id',$id)->delete();



Question: What is Response in Laravel?
Following are different type of responses?
  1. View Responses
  2. JSON Responses
  3. File Downloads
  4. File Responses
  5. Response Macros
  6. Redirecting To Named Routes
  7. Redirecting To Controller Actions
  8. Redirecting To External Domains
  9. Redirecting With Flashed Session Data



Question: How to get current environment in Laravel?
$environment = App::environment();


Question: Where do you locate database configuration file?
Migrations are like version control for your database, that's allow to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.


Question: What are laravel 6 features?
  1. Inbuilt CRSF (cross-site request forgery ) Protection.
  2. Inbuilt paginations
  3. Reverse Routing
  4. Query builder
  5. Route caching
  6. Database Migration
  7. IOC (Inverse of Control) .
  8. Job middleware
  9. Lazy collections



Friday, 3 April 2020

Laravel interview questions for 3 year experienced

Laravel interview questions for 3 year experienced

Question: Explain validation in Laravel.?
ValidatesRequests is the trait which is been used by Laravel classes for validating input data.
public function store(Request $request)
{
   $validatedData = $request->validate([
       'title' => 'required|unique:posts|max:255',
       'description' => 'required',
       'email' => 'required',
   ]);
}



Question: What is CSRF protection and CSRF token?
Cross-site forgeries are a type of malicious exploit where unauthorized person/command do/run on behalf of the authenticated user.
Laravel generates a CSRF "token" automatically for each active user session.
This token is used to verify that the authenticated user is the one actually making the requests.


Question: What is Laravel Dusk?
It is expressive, easy-to-use browser automation and testing API.


Question: What is Laravel Echo?
Event broadcasting, evolved. Bring the power of WebSockets to your application without the complexity.


Question: How do you install Laravel?
Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure we have Composer installed on your machine.


Question: Explain Binding Instances?
You may also bind an existing object instance into the container using the instance method.
$api = new HelpSpot\API(new HttpClient);
$this->app->instance("HelpSpot\API", $api);



Question: Explain Extending Bindings?
$this->app->extend(Service::class, function($service) {
    return new DecoratedService($service);
});



Question: What is the make Method?
You may use the make method to resolve a class instance out of the container.
$api = $this->app->make("HelpSpot\API");



Question: What is Register Method?
within the register method, you should only bind things into the service container.


Question: What is the Boot Method?
if we need to register a view composer within our service provider? This should be done within the boot method.


Question: Where do you regiser service providers?
config/app.php configuration file


Question: What are Laravel’s Contracts?
Laravel’s Contracts are a set of interfaces that define the core services provided by the framework.


Question: Give example of Router?
Route::get("foo", function () {
return "Hello World";
});



Question: What are the available Router Methods?
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);



Question: How to 301 redirect in laravel (permanent redirect)
Route::redirect("/old", "/new", 301);



Question: How to 302 redirectin laravel (temporary redirect)
Route::redirect("/old", "/new", 302);



Question: What are Middleware Groups?
Sometimes you may want to group several middleware under a single key to make them easier to assign to routes.


Question: What are Redirect responses?
Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL.


Question: Where do you locate database configuration file?
The database configuration for your application is located at config/database.php.


Question: What are Blade Templates?
Blade is the simple, yet powerful templating engine provided with Laravel.


Thursday, 12 December 2019

How to resize images in php

How to resize images in php - with code

Function resizeImage
    
/**
 * 
 * @param type $width
 * @param type $height
 * @param type $mode
 * @param type $imageName
 * @param type $extension
 * @return string
 */
     function resizeImage($width, $height, $mode, $imageName,$extension) {
        $docRoot = getenv("DOCUMENT_ROOT");
        
        /* Get original image x y */
        $tmpNM = $_FILES['files']['tmp_name'];
        
        list($w, $h) = getimagesize($_FILES['files']['tmp_name']);
        /* calculate new image size with ratio */
        $ratio = max($width / $w, $height / $h);
        $h = ceil($height / $ratio);
        $x = ($w - $width / $ratio) / 2;
        $w = ceil($width / $ratio);
        /* new file name */
        if ($mode == 'userphoto') {
                $path = $docRoot . '/upload/userphoto/' . $imageName;
        } 
        
 
        /* read binary data from image file */
        $imgString = file_get_contents($_FILES['files']['tmp_name']);
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($width, $height);
        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
        $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
        /* Save image */
        $extension = strtolower($extension);
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
            case 'jpe':
                imagejpeg($tmp, $path, 100);
                break;
            case 'png':
                imagepng($tmp, $path,0);
                break;
            case 'gif':
                imagegif($tmp, $path, 100);
                break;
            case 'bmp':
                imagewbmp($tmp, $path);
                break;
            default:
                
                exit;
                break;
        }
        return $path;
        /* cleanup memory */
        imagedestroy($image);
       imagedestroy($tmp);
    }    



How to use Code
HTML Code

<form action="upload.php" enctype="multipart/form-data" method="post">
<input id="image upload" name="files" type="file" />
<input name="submit" type="submit" value="Upload Image" />



PHP Code
  
//List of thumbnails
$sizes = array(200 => 200, 150 => 150);

$files=array();
if (!empty($_FILES)) {
    //Clean the image name
    $_FILES['files']['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', strtolower(trim($_FILES['files']['name'])));    
    
    //Temporary file, type, name
    $tmpNM = $_FILES['files']['tmp_name'];
    $imageType = $_FILES['files']['type'];
    $imageName = $_FILES['files']['name'];
    
    //Get image extension
    $imageNameType = explode(".", $_FILES['files']['name']);
    
    //Type of images support for uploading
    $fileMimeTypes = array('image/jpeg', 'image/png', 'image/bmp', 'image/gif'); // mime  extensions
    $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
    
    if (in_array(strtolower($imageNameType[1]), $fileTypes)) {
        $fullImageName = time('his') . '_' . $_FILES['files']['name'];
        foreach ($sizes as $w => $h) {
            $files[] = $this->resizeImage($w, $h, 'userphoto', "{$w}_{$fullImageName}", $imageNameType[1]);
        }

    } 
}

Saturday, 2 November 2019

PHP interview questions and answers for 3 year experience

PHP interview questions and answers for 3 year experience

Question: Are PHP functions case sensitive?
Inbuilt function are not sensitive.
User defined functions are senstivie.

Case sensitive (both user defined and PHP defined)
  1. variables
  2. constants
  3. array keys
  4. class properties
  5. class constants

Case insensitive (both user defined and PHP defined)
  1. functions
  2. class constructors
  3. class methods
  4. keywords and constructs (if, else, null, foreach, echo etc.)






Question: How to return call by reference value from function?
Just use &(ampersand) before the function name.
For Example.
function &showData($data){
   $data.=' New String';    
   return $data;
}



Question: How to check a form is submited OR Not?
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //form is submitted
}



Question: How to remove all leading zeros from string?
echo ltrim('00000012', '0'); //12



Question: How to find HTTP Method?
$_SERVER['REQUEST_METHOD']
It will return GET, HEAD, POST, PUT etc


Question: How to Serializing PHP object to JSON?
$userModel = new UserModel();
echo json_encode($userModel);//serialize data



Question: How to get current URL of web page?
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];



Question: How to add N number of days in an data?
echo date('Y-m-d', strtotime("+30 days"));



Question: How to get Yesterday date?
echo date("F j, Y", time() - 60 * 60 * 24); //November 1, 2016


Question: What's the maximum size for an int in PHP? The size of an integer is platform-dependent
Maximum value of about two billion for 32 bit system.


Question: How to remove all specific characters at the end of a string?
$string = 'Hello. * cool';
echo $string = str_replace(array('*', '.',' '), '', $string); //Remove * . and space [you can add more as you want]




Thursday, 12 September 2019

New PHP 7 Feature List

New PHP 7 Feature List

Question: Why we should use PHP 7 as compare to PHP5?
  1. Improved performance. Its twice as fast as compare to PHP 5.
  2. Lower Memory Consumption.
  3. Scalar type declarations.
  4. Return and Scalar Type Declarations.
  5. Consistent 64-bit support
  6. Many fatal errors converted to Exceptions
  7. Secure random number generator.
  8. Various old and unsupported SAPIs and extensions are removed from the latest version
  9. NULL coalescing operator removed
  10. Anonymous Classes Added.
  11. Zero cost asserts
  12. Use of  new Zend Engine 3.0



Question: What is PHPNG?
PHPNG branch has been merged into master and has been used as the base for PHP 7.0.
PHPNG target is improve the performance and memory usage efficiency of PHP.


Question: What is a PHP parser?
PHP parser is a software which understand your coding and convert to computer language So that it can be executed & gives a output in HTML.


Question: What is a Scalar type declarations?
Allowing/prohibited datatype declaration in functions know for Scalar type declarations.
There are two options in Scalar type declarations
1) Coercive Mode (default)
2) Strict Mode
function sum(int ...$ints) {
      return array_sum($ints);
   }
   print(sum(2, '20', 4.2)); //26.2



Question: How to use return type declarations?
 function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));



Question: What is spaceship operator?
It is Operator which is used to compare two expressions.
It return -1, 0 or 1.
print( 1 <=> 1); //0
print( 1 <=> 2); //-1
print( 2 <=> 1); //1




Question: Can define accept an array?
Yes, It can. For Example:
define('CLIENTS', [
    'client 1',
    'client 2',
    'client 3'
]);



Question: What is use of Closure::call() in PHP7?
It is used to temporarily bind an object scope to a closure and invoke it.
For Example:
 class A {
      private $x = 1;
   }
   $value = function() {
      return $this->x;
   };
   print($value->call(new A));



Question: How to import import Classes using single use statement?
Before PHP 7
use com\mytestclass\ClassA;
use com\mytestclass\ClassB;
use com\mytestclass\ClassC as C;

In PHP 7
 use com\mytestclass\{ClassA, ClassB, ClassC as C};



Question: What are Deprecated features in PHP7?
Following are deprecated feature in PHP7.
  1. Old Style Constructure.
     class A {
          function A() {
             print('Deprecated');
          }
       }
    
  2. Static calls to non-static methods.
    class A {
          function b() {
             print('Deprecated');
          }
       }
       A::b();
    
    
  3. password_hash() salt



Question: What extension are removed ?
  1. ereg
  2. mssql
  3. mysql
  4. sybase_ct



Question: From where I can download PHP7?
http://php.net/downloads.php


Question: How to setup PHP7 with WampServer?
http://www.wampserver.com/en/


Question: What is Class Abstraction?
1. Classes defined as abstract may not be instantiated.
2. Class that contains at least one abstract method must also be abstract.
3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me something about Interface?
We use "interface" keyword to create class.
All methods declared in an interface must be public.
To implement an interface, the implements operator is used.
We can include multiple interface while implementing



Question: What are Traits? Give example
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits

We can create Traits as below:-
    trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }   


We can use multiple traits using comma like below
use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }

We can use one trait from another using "use"
we can also define abstract,static, data members, method




Question: What is Overloading?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
__get(), 
__set(), 
__isset() 
__unset() 
__call()
__callStatic()


Tuesday, 13 November 2018

ThinkPHP SQL queries with examples

ThinkPHP SQL queries with examples

Question: How to create Model Object?
$userObj= D("Common/Users");



Question: How to add simple AND Query?
$map=array();
$userObj= D("Common/Users");
$map['user_type'] = 2;
$map['city_id'] = 10;
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to add simple OR Query?
$map=array();
$userObj= D("Common/Users");
$map['u.username|u.email'] = 'email@domain.com';  //username OR email is email@domain.com
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use =, >, < in Query?
$map['id']  = array('eq',1000); //equal to 1000

$map['id']  = array('neq',1000); //Not equal to 1000

$map['id']  = array('gt',1000);//Greater than 1000

$map['id']  = array('egt',1000);//Greater than OR EQual 1000

$map['id']  = array('between','1,8'); //Between 1-8




Question: How to use like Query?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use like Query with NOT?
$map=array();
$userObj= D("Common/Users");
$map['b'] =array('notlike',array('%test%','%tp'),'AND'); //Not like %test% and %tp
 $lists = $userObj
                ->alias("u")                
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use Inner JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join(C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use LEFT JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('LEFT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use RIGHT JOIN ?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('RIGHT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                ->select();



Question: How to use group by and having?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $lists = $userObj
                ->alias("u") 
                ->join('RIGHT JOIN '.C('DB_PREFIX') . "profile as p ON u.id = p.uid")               
                ->where($map)
                ->order("u.id DESC")
                 ->group('u.id')                
                 ->having('count(p.id) >0')
                ->select();



Question: How to use count(for total records)?
$map=array();
$userObj= D("Common/Users");
$map['name'] = array('like','test%'); //like test%
 $count = $userObj
                ->alias("u")                 
                ->where($map)                
                ->count();



Wednesday, 20 December 2017

Encapsulation in PHP (OOP)

Encapsulation in PHP (OOP)

Question: What is Encapsulation?
The wrapping up of "Data member" and "Member functions" into a single unit (called class) is known as encapsulation.


Question: Describe the Encapsulation?
Encapsulation means hiding the internal details of an object.
OR
Encapsulation is a technique used to protect the information in an object from the other object.


Question: Give Example of the Encapsulation?
class Arithmetic {
    private $first = 10;
    private $second = 50;

    function add() {
        return $this->first + $this->second;
    }

    function multiply() {
        return $this->first * $this->second;
    }

}

//Create the object 
$obj = new Arithmetic( );

//Add Two number
echo $obj->add(); //60
//multiply Two number
echo $obj->multiply(); //500


Friday, 10 November 2017

How to replace double quoted string with bold


Question: How to replace double quoted string with bold in PHP?

$description='Hello "dude", how are you?';
echo preg_replace('/"([^"]+)"/', '<strong>$1</strong>', $description);


Output
Hello dude, how are you?




Question: How to replace bracket string with italic in PHP?

$description='Hello (dude), how are you?';
echo preg_replace('/\(([^)]+)\)/', '<i>$1</i>', $description);


Output
Hello dude, how are you?



Tuesday, 22 August 2017

How to check if port is active OR Not?

How to check if port is active OR Not?

Question: What is fsockopen?
fsockopen — Open Internet or Unix domain socket connection.


Question: How to check if port is open OR Not in particular IP Address OR Domain?
function pingDomainWithPort($domain='localhost',$port=80){
    $starttime = microtime(true);
    $file      = @fsockopen($domain, $port, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0; //in active

    if (!$file) { 
        $status = -1;  // Site is down

    } else {

        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

pingDomainWithPort($_SERVER['REMOTE_ADDR'],1935);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],1458);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],80);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],8080);

You can pass the domain name or Ip Address.


Thursday, 17 August 2017

PHP Technical Interview Questions and Answer for 2 year experienced

PHP Technical Interview Questions and Answer for 2 year experienced

Question: What is the use of the @ symbol in PHP?
It suppresses error messages, means hide the error/warning messages for that statement.
echo $noDefinedVar;



Question: How to enable all error in PHP?
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Question: How to disable all error in PHP?
ini_set('display_startup_errors', 0);
ini_set('display_errors', 0);
error_reporting(0);

Question: How to convert a variable to string?
$myVar='123456987';
$myText = (string)$myVar; // Casts to string
var_dump($myText);

Question: How to POST request with PHP?
$ch = curl_init();
$postData='var1=value1&var2=value2&var3=value3';
curl_setopt($ch, CURLOPT_URL, "http://mydomain.com/ajaxurl");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

echo $result;die;



Question: Formatting a number with leading zeros in PHP?
echo sprintf('%08d', 1234567); //01234567
echo sprintf('%09d', 1234567); //001234567
echo sprintf('%010d', 1234567); //0001234567



Question: How to Check if PHP session has already started?
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


Question: Why do we use ob_start()?
define ("FRUITS", serialize (array ("apple", "mongo", "banana","fig")));
$fruits = unserialize (FRUITS);
print_r($fruits);



Question: How to increase PHP Execution Time?
ini_set('max_execution_time', 300);



Question: how do you change the key of an array element?
$array= array ('a'=>"apple", 'm'=>"mongo", 'b'=>"banana",'f'=>"fig");
print_r($array);
$array['bbbbb']= $array['b'];
unset($array['b']);
print_r($array);



Question: How to get last key in an array?
$array= array ('a'=>"apple", 'm'=>"mongo", 'b'=>"banana",'f'=>"fig");
end($array);
echo key($array);//k



Question: Set HTTP header to UTF-8 using PHP?
header('Content-Type: text/html; charset=utf-8');



Question: How to generate a random, unique, alphanumeric string?
echo md5(uniqid(rand(), true));



Question: How to run SSH Commands from PHP?
$connection = ssh2_connect('HOST_OR_IP_ADDRESS', 'PORT');
ssh2_auth_password($connection, 'USERNAME', 'PASSWORD');

$stream = ssh2_exec($connection, 'ls');
if ($stream) {
        echo "fail: unable to execute command\n";
    } else {
        // collect returning data from command
        stream_set_blocking($stream, true);
        $data = "";
        while ($buf = fread($stream,4096)) {
            $data .= $buf;
            $data.="\n";
        }
        fclose($stream);

        echo $data;
    }



Question: What is output of below?
$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;

output
21, 21



Friday, 11 August 2017

PHP Technical Interview Questions and Answer for 3 year experienced

PHP Technical Interview Questions and Answer for 3 year experienced

Question: What is output of below script?
var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);

Output
var_dump(0123 == 123);//false
var_dump('0123' == 123); //true
var_dump('0123' === 123);//false



Question: What is output of below script?
var_dump(true and false);
var_dump(true && false);
var_dump(true || false);

Output
var_dump(true and false); //false
var_dump(true && false); //false
var_dump(true || false); //true



Question: What is output of below script?
$a1=true and false;
$a2=true && false;
$a3=true || false;

var_dump($a1);
var_dump($a2);
var_dump($a3);

Output
$a1=true and false;
$a2=true && false;
$a3=true || false;

var_dump($a1);//true
var_dump($a2);//false
var_dump($a3);//true



Question: What is output of below script?
echo  10 + "10%" + "$10";

Output
echo  10 + "10%" + "$10"; //20

Reason: First 10 is 10
Second 10 is 10
Third 10 is 0 (Because start with $)


Question: What is output of below script?
$text = 'HELLO';
$text[1] = '$';
echo $text;

Output
$text = 'HELLO';
$text[1] = '$';
echo $text;//H$LLO 


Question: What is output of below script?
$x = NULL;
var_dump($x);

Output
$x = NULL;
var_dump($x);/null


Question: Why do we use ob_start()?
Ob_start used to active the output buffering .


Question: What is a .htacces file?
.htaccess is a configuration file running on server.
Following task can be done with .htacces?
  1. URL Rewrite
  2. Website password protected.
  3. Restrict ip addresses
  4. PHP/Apache Configuration
  5. Set browser caching for Speed up application.


Question: What is the difference between compiler language and interpreted language?
Interpreted language executes line by line, if there is some error on a line it stops the execution of script. Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script ,if there is some error on some line.


Question: What is type hinting?
Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an error will occur.



Question: What will be output of following?
$x = 5;
echo $x;
echo "
"; echo $x+++$x++; echo "
"; echo $x; echo "
"; echo $x---$x--; echo "
"; echo $x;



Output
5
11
7
1
5


Question: What will be output of following?
$a = 1;
$b = 2;
echo $a,$b;


Output
12


Question: What will be output of following?
var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);


Output
boolean false
boolean true
boolean false


Thursday, 10 August 2017

PHP Interview Questions and Answer for 3 year experienced

PHP Interview Questions and Answer for 3 year experienced

Question: What is the difference between Unlink And Unset function In PHP?
unlink It is used to delete the file permanent.
unlink("/data/users.csv");
Unset It is used to delete the variable.
unset($newVariable);



Question: What are PHP Traits?
It is a mechanism that allows us to do code reusability the code and its similer as that of PHP class.
trait Goodmorning {

    public function goodmorning() {
        echo "Good Morning Viewer";
    }

}

trait Welcome {

    public function welcome() {
        echo "Welcome Viewer";
    }

}

class Message {

    use Welcome,
        Goodmorning;

    public function sendMessage() {        
        echo $this->welcome();        
        echo $this->goodmorning();
    }

}

$o = new Message;
$o->sendMessage();

Output
Welcome Viewer
Good Morning Viewer 



Question: How to get URL Of The Current Webpage??
Client side, connect with  parameter



Question: What Is Autoloading Classes In PHP? and how it works?
With autoloaders, PHP allows the to load the class or interface before it fails with an error.
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2();



Question: What s The use of ini_set()?
PHP allows the user to modify its settings mentioned in php.ini using ini_set();
For Example
Display error on page
ini_set('display_errors', '1');

Set mysql connection timeout
ini_set('mysql.connect_timeout',100);

Set maximum execution time
ini_set('max_execution_time',100000);

Set post max size
ini_set('post_max_size','30000M');

Set upload max file size
ini_set('upload_max_filesize','64000M');




Question: Which PHP Extension Helps To Debug The Code?
The name of that Extension is Xdebug.
It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.


Question: How can we get the properties of browswer?
$_SERVER['HTTP_USER_AGENT']



Question: How to get/set the session id?
Set the session Id
session_id($sessionId)

Get the session Id
echo session_id()



Question: What is Scrum?
Scrum is an Agile framework for completing complex projects.
Scrum originally was made for software development projects, but it works well for any complex and innovative scope of work.


Question: What are the ways to encrypt the data?
md5() – Calculate the md5 hash of a string.
sha1() – Calculate the sha1 hash of a string.
hash() – Generate a hash value.
crypt() – One-way string hashing.


Question: How to get cookie value?
$_COOKIE ["cookie_name"];



Question: What is use of header?
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output.


Question: What is Type juggle in PHP?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used.
If an integer value assign to variable it become integer.
If an string value assign to variable it become string.
If an object assign to variable it become object.


Question: What will be output of following?
$x = true and false and true;
var_dump($x);


Output
boolean false


Question: What will be output of following?
$text = 'Arun ';
$text[10] = 'Kumar';
echo $text;


Output
Arun K


Question: What is 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');


Friday, 4 August 2017

php amazing question and logical answer

php  amazing question and logical answer

Question: What is output of 1...1?
Its Output is 10.1
How?
Divide it into three points.
1.
.
.1

  1. 1.0 is equal to 1
  2. 2nd . is a concatenation operator
  3. .1 is equal to 0.1
  4. So {1} {.} {0.1} is EQUAL to 10.1



Question: What is final value of $a, $b in following?
$a = '1';
$b = &$a;
$b = "2$b";
echo $a;
echo $b;
output
21
21

Explaination
$a = '1'; //1
$b = &$a; //both are equal
$b = "2$b"; //now $b=21
echo $a;  //21
echo $b; //21



Question: What is output of 016/2?
Output is : 7. The leading zero indicates an octal number in PHP, so the decimal number 14 instead to decimal 16;
echo 016; //14
echo 016/2; //7



Wednesday, 26 July 2017

PHP interview questions and answers for 4 year experience

PHP interview questions and answers for 4 year experience

Question: Difference between include and require?
include: It include a file, It does not find through an warning.
require: It include a file, It does not find through an fatal error, process exit.


Question: How to get IP Address of client?
$_SERVER['REMOTE_ADDR'];



Question: How to get IP Address of Server?
$_SERVER['SERVER_ADDR'];



Question: What is output of following?
$a = '10';
$b = &$a;

$b = "2$b";

echo $a;
echo $b;

Output
210
210



Question: What are the main error types?
  1. Notices: Simple, non-critical errors that are occurred during the script execution.Ideally we should fix all notices.
    echo $undefinedVar;
    
  2. Warning: more important than Notice but it is also non-critical errors that are occurred during the script execution. It should be fixed.
    include "non-ExistFile.php";
    
  3. Error: critical errors due to which script execution stopped. It must be fixed.
    require "non-ExistFile.php";
    



Question: How to enable/disable error reporting?
Enable error
error_reporting(E_ALL);

Disable error
error_reporting(0);



Question: What are Traits?
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.
Example of Traits
trait users {
    function getUserType() { }
    function getUserDescription() {  }
    function getUserDelete() {  }
}

class ezcReflectionMethod extends ReflectionMethod {
    use users;    
}

class ezcReflectionFunction extends ReflectionFunction {
    use users;
}



Question: How to extend a class defined with Final?
No, You can't extend. A class declare with final keyword can't be extend.


Question: What is full form of PSRs?
PHP Standards Recommendations


Question: What is the difference between $message and $$message?
$message is a simple variable whereas $$message is variable whose name is stored in another variable ($message).


Question: How to destroy the session?
session_destroy



Question: How do you execute a PHP script from the command line?
  1. Get the php.exe path from server (My PHP path is : D:\wamp\bin\php\php5.5.12)
  2. In environment variable, Add this path path under PATH variable.
  3. Re-start the computer.
  4. Now, you can execute php files from command file.
    php hello.php



Question: How to repair the session?
REPAIR TABLE tablename 
REPAIR TABLE tablename QUICK 
REPAIR TABLE tablename EXTENDED 



Question: Are Parent constructors called implicitly inside a class constructor?
No, You need to call explicitly.
parent::constructor($value);



Question: What does $_GLOBALS means?
It is associate variable which have all the global data of GET/POST/SESSION/_FILES/ENV/SERVER/GLOBALS etc.
Array
(
    [_GET] => Array
        (
        )

    [_POST] => Array
        (
        )

    [_COOKIE] => Array
        (    
            [_gu] => 1cf7097e-eaf0-486d-aa34-449cf1164ba8
            [_gw] => 2.127103(sc~1,s~oru42c,a~1)127418(sc~1,s~oru42c)u[~0,~0,~0,~0,~0]v[~ev3o1,~4,~0]a()
            [PHPSESSID] => ki18pnad1knttqv5i6233sjem7
        )

    [_FILES] => Array
        (
        )

    [_ENV] => Array
        (
        )

    [_REQUEST] => Array
        (
        )

    [_SERVER] => Array
        (            
            [REQUEST_TIME_FLOAT] => 1501064295.228
            [REQUEST_TIME] => 1501064295
        )

    [GLOBALS] => Array
 *RECURSION*
    [_SESSION] => Array
        (
        )

)



Question: How is it possible to parse a configuration file?
parse_ini_file('config.ini');


Question: What is the difference between characters \034 and \x34? \034 is octal 34 and \x34 is hex 34.


Question: Explain soundex() and metaphone().?
soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word.
$str= "hello";
Echo soundex($str);

metaphone() the metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if pronounced by an English person.

Question: How to start displaying errors in PHP application ? 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




Question: What is stdClass?
It is PHP generic empty class.
stdClass is used to create the new Object. For Example
$newObj = new stdClass();
$newObj->name='What is your name?';
$newObj->description='Tell me about yourself?';
$newObj->areYouInIndia=1;
print_r($newObj);

Output
stdClass Object
(
    [name] => What is your name?
    [description] => Tell me about yourself?
    [areYouInIndia] => 1
)



Question: What is output of below?
$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;

output
21, 21


Question:What is the difference between GET and POST?
  1. GET displays the submitted data as part of the URL whereas post does not show.
  2. GET can handle a maximum of 2048 characters, POST has no such restrictions
  3. GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
  4. Normally GET is used to retrieve data while POST to insert and update.



Question:What is traits and give example?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();


output
Hello World