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()