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

    } 
}

Sunday 8 December 2019

Swagger - REST API documentation tool

Swagger - REST API documentation tool


Question: What is swagger?
It is REST API documentation tool which is used to list the APIs and view the request and response.
In this, we need to add some annotations in your functions and then it will automatically generate a beautiful and user-friendly documentation for your APIs.



Question: Where it is used?
Whenever we develop an android, IOS (Apple) application, we need to create an APIs for them.

To check the API details (URL, Request, response), we use Swagger.


Question: Who is using swagger?
Backend Developer: developer used it while creating Or updating an API.
Team Leader: As it give List of APIs with request and response. Team leader used it review the APIs.
Android/IOS Developer: While integrating the APIs, Its quite help the developer because they can check the response of APIs with different request.


Question: What are benefits of swagger?
  1. Its give list of APIs with short description.
  2. Its give the Request and Response of API.
  3. We can test the response of API with different request.
  4. We need to integrate in application first time, after the we need to add some annotations in functions/APIs.
  5. Can be integrate in Core PHP or Framework.
  6. We need not to list and details of apis manually.



Question: What is Swagger Editor?
The Swagger Editor is the tool for quickly getting started with the Swagger Specification.
Create new APIs OR update existing ones in a powerful Editor which visually renders your Swagger definition and provides real time error-feedback.
http://editor.swagger.io/#/


Question: Give a Demo URL?
http://petstore.swagger.io/


Question: From where i can download?
http://swagger.io/docs/#swagger-ui-documentation-29


Question: How to Add API in swagger?
Add Following code before the class declaration
/**
 * @SWG\Resource(
 *     apiVersion="1.0",
 *     swaggerVersion="1.2",
 *     description="Search users"
 * )
 */



Question: How to add new Operation for an API?
Add Following code before the method declaration
    /**
     * @SWG\Api(
     *     path="/search",
     *     @SWG\Operation(
     *         method="POST",
     *         summary="Get users near your location",
     *         type="Users list",
     *         @SWG\Parameters(
     *             @SWG\Parameter(
     *                 name="interests",
     *                 paramType="form",
     *                 description="comma seperated looking for",
     *                 required=false,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *             @SWG\Parameter(
     *                 name="page",
     *                 paramType="form",
     *                 description="page number",
     *                 required=true,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *         ),
     *         @SWG\ResponseMessage(code=400, message="Invalid Data")
     *     )
     * )
     */



Difference between channel and playlist on youtube

Difference between channel and playlist on youtube

A channel is your identity on YouTube, like your name, where your upload videos.
OR
A channel  is the home page for an your youtube account.

Question: What details are available on Channel page?
--- Basic information like Your Name, Account type etc.
--- Your public videos which you have uploaded.
--- Listing of playlist.


Question: What we can do on Channel page?
--- Update your information. --- upload videos.
--- customize the color theme of your channel.
--- Others can subscribe your channel.



Question: Sample of Youtbe Channel?
https://www.youtube.com/channel/UCFPS0qKgr-GbSRAppOkdpUA



Question: What is playlist?
A playlist is a collection of videos you may saved.


Question: List of Playlist (After Login on youtube.com with your gmail.com account)
https://www.youtube.com/view_all_playlists


Create a New Playlist (After Login on youtube)
https://www.youtube.com/view_all_playlists
Click on "New Playlist", an popup will prompt, just add the your playlist name


Question: How to add videos in playlist?
Go to playlist page (Like https://www.youtube.com/playlist?list=PLREKFLRZTg5xJJHmLiKZ0VBTKpubGXksb).
Click on "Add Videos" (Middle Right side).
An Popup will prompt.
Just add the YouTube video URL (Any video which you like) and follow Steps.


Question: What you can do with your playlist?
--- Make the playlist as public/private.
--- Add notes to each videos.
--- Re-ordering the videos.
--- AutoPlay on/off for videos.
--- Share your playlist on Fb.
--- Embed your playlist videos in your website/blog.



Question: Need Playlist Sample URL

https://www.youtube.com/playlist?list=PLREKFLRZTg5xJJHmLiKZ0VBTKpubGXksb



Question: Can we earn money with playlist?
No, You can't earn money on other's video (Uploaded by other).
You can earn money with your own videos (uploaded by you)



Saturday 7 December 2019

How to Validate email address in PHP?


How to Validate email address in PHP?


Following are in built PHP function to validate the email address and Ip Address.


Validate Email - Example 1
$email='helo@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}

helo@gmail.com - Valid

Validate Email - Example 2
$email='464646@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. '- Invalid'; 
}else{
echo $email. ' - Valid';     
}

464646@gmail.com - Valid

Validate Email - Example 3
$email='arunkumar.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}


arunkumar.com - Invalid



Validate IP Address - Example 1
Question: How to Validate IP Address?
$ipAddress = '127.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is Valid.";
}

127.0.0.1 is Valid

Validate IP Address - Example 2
$ipAddress = '127.test.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is In-Valid.";
}

127.test.0.0.1 is Valid


Validate URL - Example 1
$ipAddress = '127.test.0.0.1';
$website = 'https://www.web-technology-experts-notes.in';
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  echo   "Invalid URL";
}else{
echo   "Valid URL";
}

Valid URL

Friday 22 November 2019

How to setup different configs in server (development, production)?

How to implement different configs for development, production?

Question: How to implement different configs for development, production etc?
  1. Added following line in .htacess (Location: /public/.htaccess)
    SetEnv APPLICATION_ENV development
    This is for development.
  2. Open application.config.php in /config/application.config.php
  3. Get the current environment.
    $applicationEnv = getenv('APPLICATION_ENV');

    Dynamic the file like below:
            'config_glob_paths' => array(         
                "config/autoload/{,*.}{$applicationEnv}.php"
            )
  4. Create the config files like below in /config/autoload
    development.php
    production.php
    
  5. Below are the sample of config file.
    return array(
        'db' => array(
            'driver' => 'Pdo',
            'dsn' => 'mysql:dbname=DBNAME;host=HOST',
            'username' => 'DB_USERNAME',
            'password' => 'DB_PASSWORD'
        )
    );
    Please update the database credentials.

Saturday 16 November 2019

How to Send Tweets automatically with PHP?

How to Send Tweets automatically with PHP?


Basic Requirements
  1. An Twitter account.
  2. An Twitter app. If don't have please create @ https://apps.twitter.com
  3. Twitter Auth REST API, If don't have please download from https://github.com/abraham/twitteroauth
  4. An Server, You can also test in local wampserver or xampserver


How to Send Tweets automatically with PHP, Follow following Steps:
  1. Include twitter files.
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/twitteroauth.php');
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/config.php');
  2. Collect all constants values from your twitter app (i.e apps.twitter.com)

  3. Add constants in TwitterOAuth constructor.
    define('CONSUMER_KEY', 'YOUR_KEY');
    define('CONSUMER_SECRET', 'YOUR_SECRET_KEY');
    define('ACCESS_TOKEN', 'YOUR_TOKEN');
    define('ACCESS_TOKEN_SECRET', 'YOUR_TOKEN_SECRET');
    
  4. $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  5. Now post the message.
    $message='This is test tweet.';
    $twitter->post('statuses/update', array('status' => $message));
  6. Refresh the twitter.com, you will see your message at top of page.

Saturday 9 November 2019

Paypal Mass Payment - Pay with email Address

Paypal Mass Payment - Pay with email Address

Mass Pay. Merchants can use the Mass Pay API to send money instantly to multiple recipients at once.


Question: Can I pay someone with their email address (Manual Transaction)?
Yes, you can pay.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: When money will be credited to the receiver account(Manual Transaction)?
When you pay with email address and that email is already register with paypal.
Money will be credited immediately.

If email address is not registered, then receiver will get an email from paypal and he need to follow the steps in email to received.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: What are transaction charges (Manual Transaction)?
If you are paying to your friend/family member and they are within same country - Its Free.
If you are paying for commerical purpose, No transaction charges for Sender/Buyer and (2.3% +.30 USD) will be deducted from seller/reciever.


Question: Can I can Cancel the payment after sending?
You can cancel only if he has not accept the payment.
but receiver can refund money to you.


Question: Is there any API available to pay with email address?

You can use MassPay API OR Adaptive Payments API. Question: What is Mass Paypal?
In this case, One Merchant can send the money to his partner's paypal email address (Paypal email address), mean each merchant must have paypal account. https://developer.paypal.com/docs/classic/mass-pay/integration-guide/MassPayOverview/


Question: What are keys of Mass Paypal through API?
  1. When we send payment with email address PayPal takes the payment amounts from your account and attempts to put them into the recipients' PayPal account.
  2. If the recipients do not have PayPal accounts, PayPal notifies them that a payment is available and they must create a PayPal account to receive the payment.
  3. Payments processing can take from a couple of minutes to several hours.
  4. PayPal will temporarily hold the total monetary value of the mass payment, plus associated fees, until processing is completed.
  5. If a payment is sent to a recipient who does not have a PayPal account, and it remains unclaimed for 30 days from the payment date, the money is returned to your PayPal account.
  6. Mass Payments need to enable for PayPal.
  7. You can only cancel payments that have an unclaimed payment.



Question: What is Mass Paypal Request parameter?
Array
(
    [METHOD] => MassPay
    [USER] => testname_api1.no-spam.ws
    [PWD] => 55555526677
    [SIGNATURE] => Alsdfdsfafdsfs.zYsROoDYkL2AigOq
    [VERSION] => 95
    [RECEIVERTYPE] => EmailAddress
    [CURRENCYCODE] => USD
    [L_EMAIL0] => testnamel@no-spam.ws
    [L_AMT0] => 10.00
    [L_EMAIL1] => testname2@no-spam.ws
    [L_AMT1] => 10.00
)