Saturday 30 May 2020

PHP 7 Scalar type declarations and return type declarations

PHP 7  Scalar type declarations and return type declarations

What is a Scalar type declarations?
Allowing/Not-Allowing datatype declaration in functions is known as Scalar type declarations.


Question: What are different types of Scalar type declarations?
1) Coercive Mode (default)
2) Strict Mode


What are different type of data-type can be used in Scalar type declarations?
  1. int
  2. float
  3. bool
  4. string
  5. interfaces
  6. array
  7. callable



Question: Give the examples of Scalar type declarations with Coercive Mode (default)
Example 1
$a=1; // integer
$b=2; //integer
function FunctionName1(int $a, int $b){
return $a + $b;
}
echo FunctionName1($a, $b); //3


Example 2
   function sum(int ...$ints) {
      return array_sum($ints);
   }

   print(sum(3, '2', 5.1)); //10


Example 3
function FunctionName3(int $a, int $b){
return $a * $b;
}

echo FunctionName3('hello', 10); //PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given.


Example 4
$a='1One'; 
$b=2; //integer
function FunctionName3(int $a, int $b){
return $a + $b;
}
echo FunctionName3($a, $b);//RESULT: PHP Notice: A non well formed numeric value encountered on line 5


Question: Give the examples of Scalar type declarations with STRICT MODE?
Example 1
declare(strict_types=1); 

$a=1; // integer
$b=2; //integer
function phpFunction (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//3

Example 2
declare(strict_types=1); 

$a='1'; // String
$b=2; //integer
function phpFunction1 (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//Fatal error: Uncaught TypeError: Argument 1 passed to phpFunction1() must be of the type int, string given


Question: Give the examples of Return type declarations with STRICT MODE?
Example 1
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : int  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);


Example 2
declare(strict_types=1); 
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : string  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);//PHP Fatal error:  Uncaught TypeError: Return value of phpFunctionReturn() must be of the type string, integer returned in /home/cg/root/7035270/main.php:6




Friday 29 May 2020

CSS3 interview questions and answers for experienced

css3 interview questions and answers for experienced



Question: How to write conditional statement in CSS?
<!--[if IE 7]>
<style type="text/css">
div.abc {                 
    background-color:red;
}
</style>
<![endif]-->



Question: How to write styles for all html elements of the same type?
Use tag name to write the CSS.
See Example
h1{font-size:18px;}
h2{font-size:17px;}
h3{font-size:16px;}
h4{font-size:15px;}



Question: What are different vaules of position attributes?
absolute
fixed
inherit
relative
static


Question: How to display a link without underline using CSS?
 a{
    text-decoration:none;
}



Question: How to display a link without underline when mouseover on the link using CSS?
 a:hover{
    text-decoration:none;
}



Question: How to page break after an html element in CSS?
<div style="page-break-after: always;">
Web Technology Experts Notes</div>



Question: What is the default value of "position" attribute in css?
static


Question: How we can specify more than one css class for any HTML element?
<div class="class1 class2">
Web technology experts Notes</div>




Question: Is CSS case sensitive?
No


Question: What is ID selector?
ID selector is an individually identified selector to which a specific style is declared.



Question: How to set wait cursor?
div.click{
    cursor:wait;
}




Question: What is Tweening ?
It process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image.

Question: What are Child Selectors?
A child selector is used when you want to match an element that is the child of another specific element.
div.abc > ul {font-weight: bold;}



Question: What are different ways to apply styles to a Web page
Inline
Embedded
Linked
Imported



Question: What is contextual selector
Contextual selector addresses specific occurrence of an element.




Question: How to disable text selection highlighting with CSS?
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}

Add the .noselect to the html tag





Saturday 18 April 2020

How to check if a number is prime?

How to check if a number is prime?


Question: What is Prime Number
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.


Question: Give the example of Prime Number
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.


Question: Write an function that check the prime number OR Not?
function checkPrime($number){
    if($number < 0 ){
        return false;
    }
    $return=true;
    for($i=2; $i < $number; $i++){
        if($number % $i ==0){
            $return=false;
            break;
        }
    }
   return $return;
}



Question: How to check a number is prime Or Not?
echo checkPrime(2)?'Prime':'Not Prime'; //Prime
echo checkPrime(4)?'Prime':'Not Prime'; //Not Prime
echo checkPrime(6)?'Prime':'Not Prime'; //Not prime
echo checkPrime(7)?'Prime':'Not Prime';  //Prime


Question: What are the prime numbers between 1 to 100?
for( $i = 2; $i < 100; $i++ ){
    if( checkPrime( $i ) ){
        echo $i;
        echo ',';
    }
}






Wednesday 8 April 2020

Difference between mysql.createConnection and mysql.createPool in Node.js?

Difference between mysql.createConnection and mysql.createPool in Node.js?

mysql.createConnection

When you create a connection with mysql.createConnection, you only have one connection and it lasts until you close it OR connection closed by MySQL.

A single connection is blocking. While executing one query, it cannot execute others. hence, your application will not perform good.
Example:
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});


mysql.createPool

mysql.createPool is a place where connections get stored.
When you request a connection from a pool,you will receive a connection that is not currently being used, or a new connection.
If you're already at the connection limit, it will wait until a connection is available before it continues.

A pool while one connection is busy running a query, others can be used to execute subsequent queries. Hence, your application will perform good.
Example:
var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});



Tuesday 7 April 2020

How to check active connections in MySQL?

How to check active connections in MySQL?

Question: How to check active connections in mysql?
show status where `variable_name` = 'Threads_connected';



Question: How to check the limit of MySQL active connections?
SHOW VARIABLES LIKE "max_connections";



Question: Display the list of active MySQL Process list?
show processlist;



Question: How to check the max no of connections used?
SHOW STATUS WHERE `variable_name` = 'Max_used_connections';



Question: MySQL set the max no of connections used (Temporarily/Quick)?
SET GLOBAL max_connections = 512;



Question: MySQL set the max no of connections used (Temporarily/Quick)?
Open my.cnf or my.ini in MySQL
max_connections = 512

service mysqld restart


Question: MySQL check number of connections throughout history?
show status like 'Connections%';

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.


Wednesday 1 April 2020

Laravel interview questions for 2 year experienced

Laravel interview questions for 2 year experienced

Question: How to get current route name and method name?
request()->route()->getName(); //Return route name
request()->route()->getActionMethod();//Return method name



Question: What do you mean by bundles?
Bundles are referred to as packages in Laravel. These packages are used to increase the functionality of Laravel.


Question: Explain important directories used in a common Laravel application.?
App/ : This is a source folder where our application code lives. All controllers, policies, and models are in this folder.
Config/ : Here are configuration files.
Database/: Houses the database files, including migrations, seeds, and test factories.
Public/: Publicly accessible folder holding compiled assets and of course an index.php file.


Question: Explain reverse routing in Laravel.
Reverse routing is a method of generating URL based on symbol or name. It makes your Laravel application flexible.


Question: Define Lumen?
Lumen framework is a smaller, and faster, version of a building Laravel based services, and REST API's.


Question: How can you generate URLs?
Laravel has helpers to generate URLs.


Question: Explain faker in Laravel?
It is a type of module or packages which are used to create fake data. This data can be used for testing purpose.


Question: List basic concepts in Laravel?
  1. Routing
  2. Eloquent ORM
  3. Middleware
  4. Security
  5. Caching
  6. Blade Templating



Question: What is Eloquent?
Eloquent is an ORM used in Laravel. It provides simple active record implementation working with the database.


Question: What is the use of DB facade?
DB facade is used to run SQL queries like create, select, update, insert, and delete.


Question: What is a session in Laravel?
Session is used to pass user information from one web page to another.
Support for cookie, array, file, Memcached, and Redis to handle session data.


Question: Explain to listeners?
Listeners are used to handling events and exceptions.


Question: What are policies classes?
Policies classes include authorization logic of Laravel application.


Question: What is an Observer? Observeris used to make clusters of event listeners for a model.
Method names of these classes depict the Eloquent event. Observers classes methods receive the model as an argument.

Question: What is the use of the bootstrap directory?
It is used to initialize a Laravel project. This bootstrap directory contains app.php file.


Question: Where will you define Laravel's Facades?
In Illuminate\Support\Facades namespace.


Question: Name databases supported by Laravel.
  1. MySQL
  2. SQLite
  3. SQL Server
  4. PostgreSQL



Question: What is the default session timeout duration?
2 hours.


Question: How to remove a complied class file?
Use clear-compiled command.


Question: In which folder robot.txt is placed?
Robot.txt file is placed in Public directory.


Laravel interview questions for 1 year experience

Laravel interview questions for 1 year experience

Question: How to make a helper file in laravel?
  1. Please create a app/helpers.php file in app folder.
  2. Add Following in in autoload variable.
    "files": [
        "app/helpers.php"
    ]
  3. Now update your composer.json
    composer update



Question: How to use mail() in laravel?
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('from@example.com', 'Send Name');
    $m->to('receiver@example.com', 'Receiver Name')->subject('Your Reminder!');
});



Question: What is a REPL?
REPL is a type of interactive shell that takes in single user inputs, process them, and returns the result to the client. The full form of REPL is Read—Eval—Print—Loop


Question: How to use update query in Laravel?
Use Update function. for example
Blog::where(['id' => 10023])->update([
   'title' => 'Interview Questions',
   'content’ => 'Web Technology exerts notes'
]); 



Question: How to use multiple OR condition in Laravel Query?
Blog::where(['id' => 10023])->orWhere(['username’ => 'username12'])->update(['title' => 'Interview Questions',]);



Question: What are different type of where Clauses in Laravel?
  1. where()
  2. orWhere()
  3. whereBetween()
  4. orWhereBetween()
  5. whereNotBetween()
  6. orWhereNotBetween()
  7. wherein()
  8. whereNotIn()
  9. orWhereIn()
  10. orWhereNotIn()
  11. whereNull()
  12. whereNotNull()
  13. orWhereNull()
  14. orWhereNotNull()
  15. whereDate()
  16. whereMonth()
  17. whereDay()
  18. whereYear()
  19. whereTime()
  20. whereColumn()
  21. orWhereColumn()
  22. whereExists()



Question: What is updateOrInsert method? Give example?
updateOrInsert() method is used to update an existing record in the database if matching the condition or create if no matching record exists.
Blog::updateOrInsert([
   'title' => 'Interview Questions',   
]); 



Question: How to check table is exists or not in our database using Laravel?
if(Schema::hasTable('users')) {
    echo "Table Exists";
} else {
    echo "Table does not exists"
} 



Question: How to check column is exists or not in a table using Laravel?
if(Schema::hasColumn('users', 'title')) ; //check whether admin table has username column
{
   echo "Column Exists in table";
}else{
    echo "Column does not Exists in table";
}



Question: What are the difference between insert() and insertGetId() in laravel?
Inserts(): This method is used for insert records into the database table.
insertGetId(): This method is used for insert records into the database table and return the autoincrement-id.


Question: What is lumen?
Lumen is a PHP framework which is a faster, smaller and leaner version of a full web application framework.


Question: What is the full form of ORM in Laravel?
Object Relational Mapping.


Question: How to get current route name and method name?
request()->route()->getName(); //Return route name
request()->route()->getActionMethod();//Return method name



Question: How to check Ajax request in Laravel?
You can use the following syntax to check ajax request in laravel.
if ($request->ajax()) {
     echo "This is ajax requrest";
}



Question: What do you mean by bundles? In Laravel, bundles are referred to as packages.
These packages are used to increase the functionality of Laravel.
A package can have views, configuration, migrations, routes, and tasks.


Question: Name databases supported by Laravel.

  1. PostgreSQL
  2. SQL Server
  3. SQLite
  4. MySQL



Monday 30 March 2020

Laravel Interview Questions and answers for Fresher

Laravel Interview Questions and answers for Fresher

Question: What are the new features of Laravel 7?
Laravel 7.0 is incorporated features such as Better routing speed, Laravel Airlock, Custom Eloquent casts, Fluent string operations, CORS support, and many more features like below.
  1. Custom Eloquent Casts
  2. Route Caching Speed Improvements
  3. HTTP Client
  4. Query Time Casts
  5. Blade Component Tags & Improvements
  6. Laravel Airlock
  7. CORS Support
  8. Fluent string operations
  9. Multiple Mail Drivers
  10. New Artisan Commands etc


Question: What is the use of dd() in Laravel?
It is a helper function which is used to dump a variable's contents to the browser.
dd($arrayData);



Question: How to make a helper file in laravel?
  1. Please create a app/helpers.php file in app folder.
  2. Add Following in in autoload variable.
    "files": [
        "app/helpers.php"
    ]
  3. Now update your composer.json
    composer update


Question: What is PHP artisan in laravel? Name some common artisan commands?
Artisan is a type of the "command line interface" using in Laravel.
It supports following commands to execute.
  1. php artisan list
  2. php artisan –version
  3. php artisan down
  4. php artisan help
  5. php artisan up
  6. php artisan make:controller
  7. php artisan make:mail
  8. php artisan make:model
  9. php artisan make:migration
  10. php artisan make:middleware
  11. php artisan make:auth
  12. php artisan make:provider etc.


Question: What is laravel Service container?
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection.


Question: How to get last inserted id using laravel query?
$blogObj = new Blog;
$blogObj->title = "Web technology experts notes";
$blogObj->save(); //Save the data 
echo $blogObj->id // Return the last inserted id


Question: How to use mail() in laravel?
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('from@example.com', 'Send Name');
    $m->to('receiver@example.com', 'Receiver Name')->subject('Your Reminder!');
});


Question: What is Auth?
Auth is in-built functionality provided by Laravel to identifying the user credentials with the database.


Question: How to make a constant? and how to use?
Add element in constants.php which should be in config folder.
return [
    'EMAIL_FROM' => 'from@example.com',
];

Get the value from config file.
echo Config::get('constants.EMAIL_FROM');//from@example.com



Question: What is with() in Laravel?
with() function is used to eager load in Laravel.


Question: How to get user’s ip address in laravel?
request()->ip()



Question: Difference between softDelete() & delete() in Laravel?
delete(): Record delete permanently.
softDelete(): records did not remove from the table only delele_at value updated with current date and time.


Question: How to enable query log in laravel?
DB::connection()->enableQueryLog();
$querieslog = DB::getQueryLog();
dd($querieslog) //Print the logs



Question: How to use skip() and take() in Laravel Query?
$posts = DB::table('blog')->skip(5)->take(10)->get();


Question: Give the list of Design Patterns in Laravel?
  1. The Builder pattern
  2. The Repository pattern
  3. The need for the Builder pattern
  4. The need for the Factory pattern
  5. The Factory pattern
  6. The Provider pattern
  7. The Facade pattern
  8. The Strategy pattern

Question: What are views?
Views contain the HTML provided by our application (UI part).


Question: What is faker in Laravel?
Faker is a type of module or packages which are used to create fake data for testing purposes.


Sunday 29 March 2020

How do I copy to the clipboard in JavaScript?

How do I copy to the clipboard in JavaScript?

Step 1: Add Following javascript function in Web page.
    function selectAllData(id) {
    var obj = document.getElementById(id);
        var text_val=eval(obj);
        text_val.focus();
        text_val.select();
        if (!document.all) return; // if IE return;
        r = text_val.createTextRange();
        r.execCommand('copy');
    }

Step 2: call selectAllData('id') function with passing the id of the container. See Example
<input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


Following are consolidate Code:

<script type="text/javascript"> function selectAllData(id) { var obj = document.getElementById(id); var text_val=eval(obj); text_val.focus(); text_val.select(); if (!document.all) return; // if IE return; r = text_val.createTextRange(); r.execCommand('copy'); }</script> <textarea cols="30" id="textareaId" row="50"> javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers javascript interview questions and answers </textarea> <input onclick="return selectAllData('textareaId')" type="button" value="Select All" />


See demo:






Question: What is the most efficient way to deep clone an object in JavaScript?
const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(), 
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);




General error: 1364 Field city_id doesn't have a default value


I have upgraded the MySQL from 5.5 to 5.6 and then getting below type of errors.
General error: 1364 Field 'city_id' doesn't have a default value

(I was not getting such type of error, it must come after upgrading my MySQL Version from 5.5 to 5.6)

Solution: It have 3 Solutions

  1. In Your Code (PHP), always set a default value (if no value) before save.
    $objSaveData->saveData(
        array(
            'id'=>111,
            'name'=>'New user',
            'city_id'=>0, //default value
        );
    );
    
  2. Create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
    like below:
    ALTER TABLE `users` CHANGE `city_id` `city_id` INT(10) UNSIGNED NOT NULL DEFAULT '0';
    
  3. Disable MySQL Strict Mode (Most appropriate)
    Disable it by setting your own SQL_MODE in the my.cnf file, then restart MySQL.

    Look for the following line:
    sql-mode = "STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
    Change it to:
    sql-mode="" 
    Restart the MySQL Service.



Saturday 28 March 2020

Laravel Interview Questions and answers

Laravel Interview Questions and answers

Question: What is Laravel?
Laravel is a free and open-source PHP framework that follows the model–view–controller design pattern.


Question: What is the latest version of Laravel?
7.0, released on 3rd March 2020.


Question: Who created Laravel?
Taylor Otwell


Question: Who created Laravel?
Taylor Otwell


Question: What language does Laravel use?
PHP


Question: Which is the best IDE for Laravel?
Netbeans,
PhpStorm,
Atom,
Sublime Text


Question: Features of Laravel?
  1. Eloquent ORM
  2. Reverse routing
  3. Restful controllers
  4. Migrations
  5. Unit testing
  6. Automatic pagination
  7. Database Seeding
  8. Query builder available



Question: What are the new features of Laravel 7?
Laravel 7.0 is incorporated features such as Better routing speed, Laravel Airlock, Custom Eloquent casts, Fluent string operations, CORS support, and many more features like below.
  1. Custom Eloquent Casts
  2. Route Caching Speed Improvements
  3. HTTP Client
  4. Query Time Casts
  5. Blade Component Tags & Improvements
  6. Laravel Airlock
  7. CORS Support
  8. Fluent string operations
  9. Multiple Mail Drivers
  10. New Artisan Commands etc



Question: How to extend login expire time in Auth?
Open config\session.php file and add/update following key's value.
'lifetime' => 180



Question: What is middleware in Laravel?
Middleware operates as a bridge and filtering mechanism between a request and response.


Question: How to pass CSRF token with ajax request?
In between head, tag put
[meta name="csrf-token" content="{{ csrf_token() }}"]


In Ajax, we have to add
$.ajaxSetup({
   headers: {
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});



Question: What is laravel Service container?
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection. Also known as the IoC container.


Question: How to use session in laravel?
Retrieving Data from session
session()->get('key');

Retrieving All session data
session()->all();

Remove data from session
session()->forget('key');

Storing Data in session
session()->put('key', 'value');


Friday 27 March 2020

Kali Linux for Beginners



Question: What is Kali Linux?
Kali Linux is open-source security packages of an ethical hacker, containing lot of tools for hacking website, wifi and networks.
Kali Linux can be installed in a machine as an Operating System.


Question: How i can download the kali linux?
https://www.kali.org/downloads/


Question: Can i installed with my current LInux/windows?
Yes, you can installed.
You can install virtual machine(VM) 
In the virtual machine, you can installed kali linux.


Question: How to update the kali linux?
Use following command in linux linux terminal.
apt-get update



Question: What is Metasploitable?
Metasploitable is an intentionally vulnerable Linux virtual machine that can be used to conduct security training, test security tools, and practice common penetration testing techniques.


Question: How to install Metasploitable machine in VM?
  1. Open link 
  2. Sign up, then it will redirect to URL where automatic zip file will be downloaded
  3. Unzip the zipped file
  4. Install Metasploitable in your virtual machine
  5. You need to browse the Metasploitable location file



Question: What is default username/password for Metasploitable machine?
username/password: msfadmin/msfadmin


Question: What is NMAP and ZenMAP?
NMAP and ZenMAP are the same tool used for the scanning phase of Ethical Hacking in Kali Linux.
NMAP uses commandline tool.
ZenMAP uses GUI


Question: What is Vega?
Vega is a free and open source scanner and testing platform to test the security of web applications.
Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities.


Question: How to install Vega?
apt-get install -y vega



Question: What is ZapProxy?
ZapProxy is an easy integrated penetration testing tool for finding vulnerabilities in web applications.


Question: What is sqlmap?
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.



Question: What is WPScan?
WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issue.


Question: What is ZapProxy?
ZapProxy is an easy integrated penetration testing tool for finding vulnerabilities in web applications.


Thursday 26 December 2019

Hadoop - Understanding Hadoop Architecture


Hadoop is an open source framework written in java that allows distributed processing of large datasets across clusters of computers.
Hadoop is designed to scale up from single server to thousands of machines and each have local-computation and storage.

Hadoop Architecture have 4 modules.

Understanding Hadoop Architecture
  1. Hadoop Common: These are Java libraries which provides filesystem and OS level abstractions which are required to start Hadoop.
  2. Hadoop YARN: This is used for job scheduling and cluster resource management.
  3. Hadoop Distributed File System: It provides high throughput access to application data and is suitable for applications that have large data sets.
  4. Hadoop MapReduce: This is YARN-based system for parallel processing of large data sets.

Question: What is MapReduce?
MapReduce is a software framework for easily writing applications which process big amounts of data in-parallel on large clusters. It consits of master JobTracker and slave TaskTracker per cluster. The JobTracker is responsible for resource management and schedule the task. TaskTracker is responsibel for execute the task.




Question: How Does HadoopwWork at very basic level?
  1. Job Submission by client to Hadoop.
  2. Input and output files are in "distributed file system" and with use of "Hadoop Common files" Initialization the hadoop.
  3. Execute of map and reduce functions.
  4. Scheduling the task by TaskTracker.
  5. Execution the task by JobTracker.

Saturday 21 December 2019

What are special characters? and how to remove special characters?

What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.


Question: Provide list of special characters?
Character Name
Space
 ! Exclamation
" Double quote
# Number sign (hash)
$ Dollar sign
 % Percent
& Ampersand
' Single quote
( Left parenthesis
) Right parenthesis
* Asterisk
+ Plus
, Comma
- Minus
. Full stop
/ Slash
 : Colon
 ; Semicolon
< Less than
= Equal sign
> Greater than
 ? Question mark
@ At sign
[ Left bracket
\ Backslash
] Right bracket
^ Caret
_ Underscore
` Grave accent (backtick)
{ Left brace
| Vertical bar
} Right brace
~ Tilde



Question: How to remove special characters from string including space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', $string);



Question: How to remove special characters from string except space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', $string);



Question: How to replace special characters with hyphen?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', $string);



Question: How to replace multiple hyphen with single hyphen?
$string='test-----ing';
echo preg_replace('/-+/', '-',$string);



Question: How to remove special characters from array?
$array=array('test !@#ing','sdalkjsad','#$#33');
function cleanData($string){
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
$array = array_map('cleanData',$array);
print_r($array);



Question: How to remove all special characters from javascript?
var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')



Monday 16 December 2019

What is CPU Usage and Memory Usage?

What is CPU Usage and Memory Usage

CPU Usage- It is the "amount of time" a CPU was used for processing the given instructions.


Memory Usage- It is the "amount of RAM" was used for processing the given instructions

Entry Processes- It is number of scripts are running at a single time. One entry process take fraction of a second to complete. So in 10 entry process you can have 10-30 visitors.

Number of Processes- It is number of process(script) can run in one time. One process take time till the execution of script.

I/O Usage- It is speed of data transfer between the hard disk and the RAM.



Question: Is high CPU usage bad?
If the CPU usage is around 100%, this means that your computer is trying to do more work than it has the capacity. Always CPU usage must be less than 90%, If so increase the CPU.




Saturday 14 December 2019

How to add number of days to a date in PHP?

How to add number of days to a date?


Program Example
$Date = "2020-09-19";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));

Output
2020-09-18
2020-09-19



Question: How to add number of days to a current date?
echo date('Y-m-d', strtotime("+10 days"));

It would add 10 days to the current date.


Question: How to subtract number of days to a current date?
echo date('Y-m-d', strtotime("-10 days"));

It would subtract 10 days to the current date.


Question: How to add number of days to a on given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()+ (3600*24*10) )); //3600 = 1 hour

It would add 10 days to the current date.


Question: How to subtract number of days to a given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()- (3600*24*10) )); //3600 = 1 hour

It would subtract 10 days to the current date.


Thursday 12 December 2019

How to get the sizes of the tables in mysql database?

How to get the sizes of the tables in mysql database?


Question: How to get the sizes of the tables in mysql database?
SELECT table_name "Table Name",SUM( data_length + index_length ) / 1024 / 1024 "Table Size (MB)",SUM( data_free )/ 1024 / 1024 "Free Space(MB)" FROM information_schema.TABLES WHERE table_schema='mydb' GROUP BY table_name ORDER BY SUM(TABLE_ROWS) DESC
(Replace mydb with Your Database Name)

Output
How to get the sizes of the tables in mysql database



Question: Get record counts for all tables along with size in MySQL database?
SELECT table_name "Table Name",SUM( data_length + index_length ) / 1024 / 1024 "Table Size (MB)",SUM( data_free )/ 1024 / 1024 "Free Space(MB)", SUM(TABLE_ROWS) AS "Total Record(S)" FROM information_schema.TABLES WHERE table_schema='mydb' GROUP BY table_name ORDER BY SUM(TABLE_ROWS) DESC
(Replace mydb with Your Database Name)

Output

Get record counts for all tables in MySQL database


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]);
        }

    } 
}