Saturday, 30 January 2016

What is Zend Engine in PHP

Zend Engine is used internally by PHP as a complier and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes. These opcodes are executed and the HTML generated is sent to the client.

What is Zend Engine



The Zend Engine is an open source scripting engine, commonly known for the important role it plays in the web automation language PHP. It was originally developed by Andi Gutmans and Zeev Suraski while they were students at the Technion - Israel Institute of Technology.

Thursday, 28 January 2016

Unix questions and answers for Root user

Unix questions and answers for Root user

Question: How to login as super admin?
Once you login in console, the root account is not active by default.
To be active as super admin, you need to execute following commands.
sudo -su root



Question: How to change the permission of folder?
chmod 755 folder 



Question: How to change the permission of multiple folder?
chmod 755 foldername1 foldername2 foldername2


Question: How to change the permission of folder in Recursive?
chmod -R 755 folder 



Question: How to change the ownership of folder?
sudo chown user:group foldername



Question: How to change the ownership of multiple folder?
sudo chown user:group foldername1 foldername2 foldername2


Question: How to change the ownership of folder in Recursive?
sudo chown -R user:group foldername



Question: How to change the folder permission only not files?
find . -type d -exec chmod 751 {} \;



Question: How to change the folder permission only in Recursive not files?
find . -type d -exec chmod -R 751 {} \;



Question: Who is login is ssh?
whoami



Question: How to change the password of user?
passwd username
(Now it will prompt for new password and re-enter password)


Question: Give example of understanding from 0-7?
Number Read (R) Write (W) Execute (X)
0 No No No
1 No No Yes
2 No Yes No
3 No Yes Yes
4 Yes No No
5 Yes No Yes
6 Yes Yes No
7 Yes Yes Yes



Sunday, 24 January 2016

Zend Framework Remember me login Form

Zend Framework Remember me login Form

Question: What is Remember Me meaning in Login Form?
When user close the browser, he logout automatically from the website due to session terminate.
When he come back on website, he need to re-login.

If we use remember me functionality, then user does not logout when he exit from website.


Question: How to use remember me in Zend Framework?
Before writing the data into session, Add following code.
Zend_Session::rememberMe(10*86400);  //Remember me for 10 days



Question: Can we use remember me with Zend_Auth?
Yes, See Example:
$result = $auth->authenticate($adapter);    
if ($result->isValid()) {
 $loginDetail = $adapter->getResultRowObject();
 $user = $adapter->getResultRowObject();   
 Zend_Session::rememberMe(7*86400); //7 days
 $namespace = new Zend_Session_Namespace('Zend_Auth'); 
 $auth->getStorage()->write($user); 
}



Question: How to keep user login even after 2 hour of inactivity?
You need to set the expiration time,
$namespace = new Zend_Session_Namespace('Zend_Auth');
$namespace->setExpirationSeconds(7*86400); // Session will expire after 7 days  



Question: What is forgetMe?
This function complements rememberMe() by writing a session cookie that has a lifetime.
Zend_Session::forgetMe(); 



Question: What is expireSessionCookie? Why It is used?
This is method of Zend_Session used for delete the session cookie in client side.

Wednesday, 20 January 2016

jQuery UI Interview Questions and Answers

 jQuery UI Interview Questions and Answers

Question: What is jQuery UI? It is JavaScript Library which is collection of jQuery widgets like datepicker, tabs, autocomplete etc. We can also add effects, interactions (drag, drop, resize) on widgets.

  Question: What widets are available in jQuery UI?
  1. Accordion
  2. Autocomplete
  3. Button
  4. Datepicker
  5. Dialog
  6. Menu
  7. Progressbar
  8. Selectmenu
  9. Slider
  10. Spinner
  11. Tabs
  12. Tooltip



Question: What are different effects available in jQuery UI
  1. Add Class
  2. Color Animation
  3. Easing
  4. Effect
  5. Hide
  6. Remove Class
  7. Show
  8. Switch Class
  9. Toggle
  10. Toggle Class



Question: In which language, JQuery UI is written?
JavaScript


Question: Is JQuery UI opensource?
Yes.
Question: What is current stable version of JQuery UI?
1.11.4 / dated 11 March 2015


Question: From where we can download the jQuery UI
https://jqueryui.com/


Question: Can we download custom widgets from jQuery UI
Yes, We can.
https://jqueryui.com/download/


Question: How to add CSS property on last div?
$('div:last').css({backgroundColor: 'green', fontWeight: 'bolder'});



Question: What is $.noConflict()?
<script src="https://code.jquery.com/jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
$.noConflict()
</script>

When we call to $.noConflict(). Old references of $ are saved during jQuery initialization, noConflict() simply restores them.


Question: Can we use another variable instead of $ in jQuery? If yes, How?
Yes, we can.
var jQ = jQuery.noConflict();
/** Now use jQ instead of $ **/
jQ( "div#pid" ).hide();



Question: How to remove close button on the jQuery UI dialog using CSS?
.ui-dialog-titlebar-close {
  visibility: hidden;
}



Question: How to remove close button on the jQuery UI dialog using JavaScript?
$("#div2").dialog({
   closeOnEscape: false,
   open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }
});



Question: How to initialize a dialog without a title bar?
var dialogOpts=[]
$("#divId").dialog(dialogOpts);
//Remove the title bar
$(".ui-dialog-titlebar").hide();



Question: How to call Hook into dialog close event in jQuery UI?
$('div#contentId').on('dialogclose', function(event) {
     //console.log('closed event called');
 });



Question: How to Download jQuery UI CSS from Google's CDN?
Uncompressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js
Compressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js



Question: How to "Change button text" in JQuery?
jQuery Version < 1.6
$("#elementId").attr('value', 'Save'); //versions older than 1.6

jQuery Version > 1.6
$("#elementId").prop('value', 'Save'); //versions newer than 1.6



Question: How can I disable a button in a jQuery ?
$('#divId').attr("disabled", true);



Question: How do I keep jQuery UI Accordion collapsed by default?
$("#divId").accordion({ header: "h4", collapsible: true, active: false });



Question: How to call a dragable widget?
// Make #draggable draggable
$(function () {
        $("#draggableDivId").draggable();
});



Question: How do I disable a jquery-ui draggable of widget?
//myObject is widget object.
myObject.draggable( 'disable' );

OR, you can set during the initalization
$("#yourDialogId").dialog({
    draggable: false
});



How to remove JQuery UI Autocomplete Helper text?
.ui-helper-hidden-accessible { display:none; }



Question: How to set year in DatePicker?
 $(".datepickerClass").datepicker({
    yearRange: '1950:2013', 
   changeMonth: true,
   changeYear: true,
   showButtonPanel: true,
   
});



Question: How to set current Date in Date Picker?
$(".datepickerClass").datepicker('setDate', new Date());



Question: How to Change Date Format in jQuery UI DatePicker?
var date = $('#datepickerDivId').datepicker({ dateFormat: 'dd-mm-yy' }).val();



Tuesday, 19 January 2016

PHP 7 new features

PHP 7 new features

Following are PHP 7 new features

  1. Scalar type declarations: In this we can declare what type of argument will be accepted by functions.
    function sumOfInts(int ...$all_ints){ /** It will accept only integers **/
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    echo sumOfInts(2, '3', 'string'); //Error: Uncaught TypeError: Argument 3 passed to sumOfInts() must be of the type integer, string given
    
  2. Return type declarations : In this we can declare what what will be the datatype from functions.
    function sumOfInts(int ...$all_ints):int
    {
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    
    Here if function "sumOfInts" return an string OR Array, it will give error.
  3. Null coalescing operator (??) have been added.
    $userId = $_GET['user_id'] ?? '0';
    is equivalent to
    $userId = isset($_GET['user_id']) ? $_GET['user_id'] : '0';
  4. Spaceship operator :The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1
    echo 1 <=> 1; // 0
    echo 1 <=> 2; // -1
    echo 2 <=> 1; // 1
    
  5. define() updates: Now you can add array.
    define('CLIENTS', [
        'client 1',
        'client 2',
        'client 3'
    ]);
    
    echo CLIENTS[1];//client 2
    
  6. Unicode codepoint escape syntax
    echo "\u{aa}";
    echo "\u{9999}";
  7. Closure::call Temporarily binding an object scope to a closure and invoking it.
    class A {private $x = 1;}
    $getX = function() {return $this->x;};
    echo $getX->call(new A);
  8. unserialize updates: Provide better security when unserializing objects on untrusted data and prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
    $data = unserialize($searilizedData, ["allowed_classes" => ["MyClass", "MyClass2"]]);
  9. list() function updates: Now list() can unpack the object also. Earlier it unpack int, float, string and array only.
  10. session_start() function updates:
    Now you can pass array-options in this function. For Example:
    session_start([
        'cache_limiter' => 'private',
        'read_and_close' => true,
    ]);
  11. intdiv() new function It performs an integer division of its operands and returns it. For Example:
    echo intdiv(100, 3); //33
  12. use updations Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement Below both are Same.
    use some\namespace\ClassA;
    use some\namespace\ClassB;
    use some\namespace\ClassC as C;
    OR
    use some\namespace\{ClassA, ClassB, ClassC as C};
  13. CSPRNG Functions i.e. random_bytes() and random_int()
    $bytes = random_bytes(5);
    var_dump(bin2hex($bytes)); //string(10) "385e33f741"
    var_dump(random_int(1, 100));//1-100
  14. Generator delegation: Generators can now delegate to another generator using yield, Traversable object/array automatically.
    function func1()
    {
        yield 1;
        yield 2;
        yield from func2();
    }
    
    function func2()
    {
        yield 3;
        yield 4;
    }
    
    foreach (func1() as $val)
    {
        echo $val, PHP_EOL;
    }
    /** Output 
    1
    2
    3
    4
    Output **/
    

Monday, 18 January 2016

Database Query in Zend framework 2

Database Query in Zend framework 2

Question: How to set database connection in Config file?
Create local.php file in config/autoload/ and following code .
return array(
'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=mydb;host=localhost',
    'username'       =>'',
    'password'      =>'',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
)
));

In controller,you can get database object
$dbObj = $this->getServiceLocator()->get('db');



Question: How to connect mysql in ZF2?
$adapter = new Zend\Db\Adapter\Adapter(array(
    'driver' => 'Mysqli',
    'database' => 'mydb',
    'username' => 'root',
    'password' => ''
 ));



Question: What are different database driver provided by ZF2 ?
  1. Pdo_Mysql: MySQL through the PDO extension
  2. Pdo_Sqlite: SQLite though the PDO extension
  3. Pdo_Pgsql: PostgreSQL through the PDO extension
  4. Mysqli: The ext/mysqli driver
  5. Pgsql: The ext/pgsql driver
  6. Sqlsrv: The ext/sqlsrv driver



Question: Can we create a new Adaper for database connection? If yes, How?
With use of following you can create your own Database adapter.
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;
See Example:
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;

class Zend\Db\Adapter\Adapter {
    public function __construct($driver, PlatformInterface $platform = null, ResultSet $queryResultSetPrototype = null)
}



Question: How to custom query in zend framework 2?
$adapter->query('SELECT * FROM `users` WHERE `embid` = ? and name like "%?%" ', array(5,'rajesh'));



Question: How to join two tables in Zend Framework2?
use Zend\Db\Sql\Select();
use Zend\Db\ResultSet\ResultSet();

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))
   ->join('profile', 'profile.user_id' = 'users.id'); //This is inner Join

$statement = $dbAdapter->createStatement();
$select->prepareStatement($dbAdapter, $statement);
$driverResult = $statment->execute();

$resultset = new ResultSet();
$resultset->initialize($driverResult); // can use setDataSource() for older ZF2 versions.

foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Expression with query in ZF2?
new \Zend\Db\Sql\Expression("NOW()");



Question:How to Add Sub Query in ZF2
$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('table1');
$subQry = $sql->select()
        ->from('md_type')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(table2.parent_id)')))
        ->where('table2.parent_id = table1.id');
$mainSelect->columns(
        array(
            'id', 
            'total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
        )
);

$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments)
foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Group By in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->group('users.first_name');



Question: How to use having clause in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name','similar_name'=>'count(first_name)'))->group('users.first_name')->having('count(first_name)>1');



Question: How to use Order By in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc');



Question: How to use limit in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc')->limit(20);


Sunday, 17 January 2016

How to load disqus when scroll to the bottom of the page?

How to load disqus when scroll to the bottom of the page?

Question: What is Disqus?
It is comment hosting service for web sites and online communities. It provide Services so that you can add comment system in your website.


Question: is Disqus multilingual?
Yes, It is.


Question: When Disqus was Launched?
October 2007


Question: Can we embed disqus in website?
Yes, you can embed.


Question: Does it provides channel for discussion?
Yes, It provides channel to discuss.


Question: What is offical website of Disqus?
http://disqus.com


Question: Can facebook user post comment using their fb account?
Yes, Facebook, twitter and google user can post comment using their account


Question: How to load disqus when scroll to the bottom of the page?
                        
  /*  CONFIGURATION VARIABLES  - MUST SET */
  var disqus_developer = 0;
  var disqus_shortname = 'aboutcity'; // required: replace example with your forum shortname                            
  var disqus_identifier = '/2015/07/ajax-technical-interview-questions-and-answers-for-experienced.html';
  var disqus_url = 'http://www.web-technology-experts-notes.in/2015/07/ajax-technical-interview-questions-and-answers-for-experienced.html';                    
  /*  CONFIGURATION VARIABLES  - MUST SET */
  
  var disqus_loaded = false;

  function load_disqus(){     
    disqus_loaded = true;
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = "http://"+disqus_shortname+".disqus.com/embed.js";       
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);

  }

/** check now bottom of page **/
  window.onscroll = function(e) {
   if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    //hit bottom of page
    if (disqus_loaded==false){ load_disqus() };
   }
  };



Saturday, 16 January 2016

Advanced PHP Interview Questions and Answers

Advanced PHP Interview Questions and Answers


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


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


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


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


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

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



Question: How To Get the Uploaded File Information in PHP Global variables?
We are all data in $_FILES variable and are following
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] – The file type determined by the browser.
$_FILES[$fieldName]['size'] – The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] – The error code associated with this file upload.


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


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


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


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


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


Question: What are the different functions in sorting an array?
Sort()
arsort()
asort()
ksort()
natsort()
natcasesort()
rsort()
usort()
array_multisort()
uksort().

Question: How can we get the browser properties using PHP?
$_SERVER['HTTP_USER_AGENT']


Question: How can I configure PHP to show error at runtime?
error_reporting(E_ALL) 



Question: How do I turn off PHP Notices?
Add following code in top of php script.
error_reporting(0);


Question: What is T_PAAMAYIM_NEKUDOTAYIM?
T_PAAMAYIM_NEKUDOTAYIM the scope resolution operator (double colon)
::


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

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

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


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


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


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


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


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



Friday, 15 January 2016

Zend Soap Client and Server

Zend Soap Client and Server

Question: What is Zend\Soap\Client?
It is component which is used to send SOAP request messages to a Web service and to receive SOAP response messages from that Web service. Zend\Soap\Client takes two parameter $wsdl, $options.
$wsdl- the URI of a WSDL file.


Question: What options are available in Zend\Soap\Client?
  1. soap_version
  2. classmap
  3. encoding
  4. wsdl
  5. uri
  6. location
  7. style
  8. use
  9. login
  10. proxy credentials like proxy_host, proxy_port, proxy_login and proxy_password
  11. local_cert
  12. compression



Question: How to call Zend\Soap\Client? Give an Example?
$client = new Zend\Soap\Client("MySoapService.wsdl");
$result1 = $client->soapMethod(10);


Question: What is Zend\Soap\Server?
Zend\Soap\Server component works in the WSDL mode, it uses WSDL document to define server object behavior and transport layer.


Question: How to call Zend\Soap\Server for Non-WSDL Mode?
For WSDL Mode
$server = new Zend\Soap\Server('MySoapService.wsdl', $options);

For Non-WSDL Mode
$server = new Zend\Soap\Server(null, $options);



Question: Where is Zend_Rest in ZF2?
Zend_Rest component is removed from zf2. Now, If you want to call rest api, you can use Zend\Http\Client

Thursday, 14 January 2016

Zend Framework 2 Http Client Curl - Zend\Http\Client

Zend Framework 2 Http Client Curl - Zend\Http\Client

Question: What is HttpClient?
HttpClient provide an easy way for performing HTTP Request.
Zend\Http\Client provide HTTP request, HTTP request with authentication and file upload, set header, set cookie etc.
After calling HTTP Request, Response object is return from Zend\Http\Response.


Question: Question: How to send request with GET Method?
use Zend\Http\Client;//Include this if you have not already included
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));
$response = $client->send();
echo $response->getBody();//This have response



Question: How to send request with POST Method?
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));

// Performing a POST request
$client->setMethod('POST');
//Set data
$client->setParameterGet(array(
   'first_name'  => 'Bender',
   'middle_name' => 'Bending',
   'last_name'   => 'Rodríguez',
   'made_in'     => 'Mexico',
));
$response = $client->send();
echo $response->getBody();//This have response



Question: How to send request on https URL?
Sometimes, Normally you can't send ajax request to https URL. In that case, you need to send SSL path.
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
   'sslcapath' => '/etc/ssl/certs'
));



Question: How to check HTTP request is successfully.?
if ($response->isSuccess()) {
    // Here is success
}



Question: What are different Adapter available in HTTP.?
Following adapters are available.
  1. Zend\Http\Client\Adapter\Socket (default)
  2. Zend\Http\Client\Adapter\Curl
  3. Zend\Http\Client\Adapter\Test
  4. Zend\Http\Client\Adapter\Proxy



Question: How to set HTTPS transport layer in Http Request?
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
    'adapter'      => 'Zend\Http\Client\Adapter\Socket',
    'ssltransport' => 'tls'
));



Question: How to set Proxy Server in Http Request?
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
    'adapter'      => 'Zend\Http\Client\Adapter\Socket',
     'adapter'    => 'Zend\Http\Client\Adapter\Proxy',
    'proxy_host' => 'proxy.int.zend2.com',
    'proxy_port' => 8000,
    'proxy_user' => 'username',
    'proxy_pass' => 'mypassword'
));



Question: Why Test Adapter are used?
Test Adapter is used to Test the API where APIs are currently not available.
For this, we use Zend\Http\Client\Adapter\Test.
In the Test Adapter, we also set the response.


Question: How can we set the cookie?
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));
//Set Single cookie
$client->addCookie('flavor', 'chocolate chips');

Set cookie from String
$cookieString = \Zend\Http\Header\SetCookie::fromString('Set-Cookie: flavor=chocolate%20chips');
$client->addCookie($cookieString);

Note, setCookies are also available.
$client->setCookies(array(
     'flavor' => 'chocolate chips',
     'amount' => 10,
 ));



Question: How to set header in Curl?
You can set the Header in http_client in following way.
$client->setHeaders(array(
    Zend\Http\Header\Host::fromString('HostName: Web technology experts Notes'),    
));

$client->setHeaders(array(    
    'Accept-Encoding' => 'gzip,deflate',
    'X-Powered-By: Web technology',
));



Question: How to upload a file in Http Client?
$client->setFileUpload('/filename.text', 'FileName');



Question: How to send xml to Http Client?

For this, you need to set the content type to text/xml.
$client->setRawBody($xml);//$xml have XML content
$client->setEncType('text/xml'); //used to set the content


Question: How to pass Brower Authentication in Http Client client?

This is used when you need to pass the Authentication to call Request.
$client->setAuth('username', 'password', Zend\Http\Client::AUTH_BASIC);



Question: What is Zend\Http\ClientStatic?
Zend\Http\ClientStatic component is static HTTP client which used to Simple Get/Post Request.


Tuesday, 12 January 2016

Zend Framework 2 form elements Filters and Validators

Zend Framework 2 form elements Filters and Validators


Question: How to bind Objects to Forms in ZF2?
$contact = new ArrayObject;
$contact['subject'] = '[Form] ';
$contact['message'] = 'Message';
$form    = new Contact\ContactForm;
/** This way we can bind the object to form **/
$form->bind($contact); 



Question: What happen when we bind an objects to Forms in ZF2?
  1. The composed Hydrator calls extract() on the object
  2. When isValid() is called and setData() is not called before, Hydrator extract values from the form object and do validation.



Question: How to create new Element in Form Object?
$form = new Zend\Form\Form()
//Add new element in form
$form->add(array(
     'type' => 'Email',
     'name' => 'email'
));



Question: How to extend existing form?
namespace Application\Form;
use Zend\Form\Form;
class MyNewForm extends Form{
    public function __construct($name = null){
        parent::__construct($name);
        $this->add(array(
            'name' => 'phone',
            'type' => 'text',
        ))
    }
}



Question: How to create form elements using Form Manager?
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Application\Form\CreatePhotoAlbum');



Question: How to create form elements and add in Form?
use Zend\Form\Element;
use Zend\Form\Form;
$checkboxElement = new Element\Checkbox('checkbox');
$checkboxElement->setLabel('Are you indian');
$checkboxElement->setUseHiddenElement(true);
$checkboxElement->setCheckedValue("yes");
$checkboxElement->setUncheckedValue("No");



Question: How to add Filter in Form?
$form = new Form\CommentForm();
$form->setInputFilter(new Form\CommentFilter());



Question: How to add validation while creating a form?
use Zend\Form\Element;
use Zend\Form\Form;

$month = new Element\Month('month');
$month->setLabel('Month')->setAttributes(array(
        'min'  => '2015-01',
        'max'  => '2017-01',
        'step' => '1', // interval is 1 month
    ));

$formObject = new Form('my-form');
$formObject->add($month);



Question: What are Form elements available in Zend Framework2?
     Button
    Captcha
    Checkbox
    Collection
    Csrf
    File
    Hidden
    Image
    Month Select
    MultiCheckbox
    Password
    Radio
    Select
    Submit
    Text
    Textarea
    Color
    Date
    DateTime
    DateTimeLocal
    Email
    Month
    Number
    Range
    Time
    Url
    Week



Question: How to display form in view phtml file?
In controller set the form.
$this->view->form = $formObject;

In View render the form.
echo $this->form;



Question: How to add input filter in Zend Form?
$inputFilterObj = new InputFilter();
$inputFilterObj->->add([
            'name' => 'profileimage',
            'type' => '\Zend\InputFilter\FileInput',
            'required' => false,
            'allow_empty' => true,
            'priority' => 300,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
            'validators' => [
                [
                    'name' => '\Zend\Validator\File\IsImage',
                ],
                [
                    'name' => '\Zend\Validator\File\UploadFile',
                ],
                [
                    'name' => '\Zend\Validator\File\ImageSize',
                    'options' => [
                        'minWidth' => 150,
                        'minHeight' => 120,
                    ]
                ],
                [
                    'name' => '\Zend\Validator\File\Size',
                    'options' => [
                        'max' => '2MB',
                    ]
                ],
            ]
        ]);



Question: How to make filed readonly in zend form?
$mobile = new Zend_Form_Element_Textarea('Name');
    $mobile->setLabel('mobile')
    ->addFilter('StripTags')
    ->addFilter('StringTrim')
    ->setOptions(array('class' => 'full-width'))
    ->setAttrib('rows', 2)
    ->getDecorator(('label'))->setOption('tag', 'span')
    ->setAttrib('readonly', 'true');;    



Saturday, 9 January 2016

XMLRPC Wordpress Attack

How to protect your wordpress website from xmlrpc attack

Queston: What is XMLRPC?
XML-RPC is one of the protocols that use XML for messages between two server. It is used to "Remote Procedure Calls" using XML.


Queston: Question: What is JSON-RPC?
JSON-RPC is one of the protocols that use JSON for messages between two server.
It is used to "Remote Procedure Calls" using JSON.


Queston: What is xmlrpc in wordpress?
WordPress uses an XML-RPC interface.
XML-RPC protocol is used to post entries.


Question: How to protect your website from xmlrpc attack?
Add following code in bottom of .htaccess file in root folder.
<Files 'xmlrpc.php'>
Order Allow,Deny
deny from all
</files>



Question: How to stop abusing XML-RPC file?
Open functions.php file in your add theme and following code.
add_filter( 'xmlrpc_methods', function( $methods ) {
         unset( $methods['pingback.ping'] );
            return $methods;
      } ); 



Thursday, 7 January 2016

OOP Interview Questions and Answers

OOP Interview Questions and Answers


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

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

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


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


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



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



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



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



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



How to call parent constructor?
parent::__construct()



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



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



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


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

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

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


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



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

class StaticClass
{
    public static $staticValue = 'foo';

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




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



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



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

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

class Class1 extends BaseClass {
    use traitSample;   
}

$obj1 = new Class1();
$obj1->getReturnType();//TraitSample:BaseClass



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



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

$obj=new TestClass();
$obj->iterateVisible(); 



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



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



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



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


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


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

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


For example
   
$str_array = array( "I", "Love", "PHP" );
$serialized_str = serialize($str_array);
echo $serialized_str;
Output
a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}




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

What can you  un-Serialize?
Resource-type

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

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