>> Difference between static class and static method approaches?
The answer is static class is one approach to make a class “Singleton”.
We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.
>> Can PHP be used for desktop applications?
Desktop Applications are one which does not need either a Web Server like IIS, Apache, PWS etc. or a web browser for their execution. ... Well, both Java and .NET can be used to build windowed applications and web pages.
Thanks to PHP-GTK, we can now build cross platform windowed applications with PHP as well.
>> What is PHP-GTK?
The PHP-GTK is a "language binding", ie it is a link between two existing languages, PHP language and GTK library.
So PHP-GTK is the PHP itself, with more features. The PHP-GTK is the first extension of the PHP language that lets you write client-side applications with GUI (Graphical User Interface).
It was written in part to prove that PHP is a language and full of great purposes.
The junction between PHP and GTK tool creates an independent platform that runs on both Linux and Windows environments.
PHP-GTK is an extension for the PHP programming language that implements language bindings for GTK+.
It provides an object-oriented interface to GTK+ classes and functions and greatly simplifies writing client-side cross-platform GUI applications.
Using PHP-GTK, you create an application that has connectivity to the server (database, access to files, etc.), like all other programs written in PHP, but that because of running on the client machine, also has full access to resources of this (run applications, write local files and access devices). For this purpose, PHP-GTK needs to be installed on each client machine that will run a PHP-GTK application.
>> PHP 7 no longer supports the mysql extension.
PHP 7 no longer supports the mysql extension, so any legacy code using the mysql extension will need to be migrated to either PDO or mysqli before it can run on a server running PHP 7 or above.
e.g.
//mysql style database connect using mysql_connect and mysql_select_db
$connection = mysql_connect( 'host', 'username', 'password', new_link,flags);
$database = mysql_select_db( 'database', $link);
//mysqli style database connect
$connection = mysqli_connect( 'host', 'username', 'password', 'database', 'port', 'socket');
>> mutator methods / gettter and setter methods in php?
“Getters” and “Setters” in PHP. “Getters” and “Setters” are object methods that allow you to control access to a certain class variables / properties. Sometimes, these functions are referred to as “mutator methods”.
A “getter” allows to you to retrieve or “get” a given property. A “setter” allows you to “set” the value of a given property.
e.g.
If we need to access or modify private variables in class then you can not access it using class object. So to get and set variables values we can use getter and setter methods.
Class Person{
private $name;
public function setName($name) {$this->name = $name;}
public function getName() {return $this->name;}
}
$person = new Person();
echo $person->name; // this will give fatal error: Cannot access private property Person::$name
$person->setName('Nilesh'); // setter to set data to class variable
$name = $person->getName(); //getter to get value of class variable
echo $name;
>> Cache SQL Results On File System?
We can use PDO object to query MySQL – IF a valid cached result does not already exist.
e.g.
$sql = "SELECT id, title, date_posted FROM posts ORDER BY date_posted DESC LIMIT 2";
$sqlCacheName = md5($sql) . ".cache";
$cache = 'cache';
$cacheFile = $cache . "/" . $sqlCacheName;
$cacheTimeSeconds = (60 * 60);//Cache time in seconds. 60 * 60 = one hour.
$results = array();
if(file_exists($cacheFile) && (filemtime($cacheFile) > (time() - ($cacheTimeSeconds)))){
//echo 'Cache file found. Use cache file instead of querying database.';
$fileContents = file_get_contents($cacheFile);
$results = json_decode($fileContents, true); ////Decode the JSON back into an array.
} else{
//echo 'Valid cache file not found. Query database.';
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$stmt = $pdo->prepare($sql); //Prepare the SQL statement.
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$resultsJSON = json_encode($results);
file_put_contents($cacheFile, $resultsJSON);
}
//Loop through the $results array, etc.
foreach($results as $row){
var_dump($row);
}
>> How to get 2nd highest salary of employee, if two employee may have same salary?
select salary from employee group by salary order by salary DESC limit 1,1
>> >> What I want to do is return an array reordered by the frequency of included terms $array = array('a', 'b', 'c', 'c', 'c', 'd', 'a', 'b', 'b', 'b', 'b');. So, like this: ['b', 'c', 'a', 'd']
Ans:
$array = array('a', 'b', 'c', 'c', 'c', 'd', 'a', 'b', 'b', 'b', 'b');
$counts = array_count_values($array); // return most repeated value as key and count as value like ['b' => 4]
arsort($counts); // sort associative array in descending to the values
$list = array_keys($counts); // get array keys
print_r($list);
//output
['b', 'c', 'a', 'd']
>> What will be output of bellow code,
<?php
session_start();
session_start();
echo "hello";
session_start();
what will be the output of above code and when session gets started?
E_NOTICE : type 8 -- A session had already been started - ignoring session_start() -- at line 3
hello
E_NOTICE : type 8 -- A session had already been started - ignoring session_start() -- at line 5
//session gets started at first line of session_start()
>> How to find duplicate email records in users table?
SELECT email, COUNT(email) AS email_count FROM `tblstuds` GROUP BY email having email_count >= 2;
>> When to use self over $this?
Use $this to refer to the current object.
Use self to refer to the current class.
>> Octal to decimal?
Base 8 is where the only numbers you can use are zero thru to seven. ie: the decimal value for 1 is represented in octal as 1 but the octal value of 8 (Decimal) is shown as 10 the value of 9 (Decimal) is 11 in octal.
e.g.
$a = 010; // decimal number is = 8( 0*8^2 + 1*8^1 + 0*8^0) = 8/4 = 2
echo $a / 4;
//output
2
>> Global variables in php?
The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
>> How can access commandline variable into php file?
We can use "$argv" variable in php to access commandline variables.
e.g.
$ php somefile.php text1Arg1 text2Arg2 text3Arg3
$argv[0] // somefile.php
$argv[1] // text1Arg1
$argv[2] // text2Arg2
$argv[3] // text3Arg3
>> Array method for arithmatic operations?
array_sum() // calculate sum and return sum integer.
>> Caching ajax call/result using jquery?
To enable ajax cache use "cache: true" in ajax method, Also set header "header("Pragma: cache");" in php file before calling ajax call.
To load faster results cache the second page output after first ajax call.
add bellow code in the php class that answers to search page ajax requests in order to send HTTP headers allowing the browser to cache the content I used a max cache lifetime of 10 minutes (600 seconds) we can revisit this limit later, if needed.
e.g.
//ajax_page.php
$seconds_to_cache = 600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
$result = array('message' => 'ajax request success');
echo json_decode($result);
$.ajax({
async: false,
url: ajax_page.php,
timeout: 20000, // 20 seconds
cache: true, // enable caching in ajax request
success: (function (res) {
$('#search-hotels').prepend(res);
}),
complete: (function () {
//cache next page
url = url.replace("page=" + page, "page=" + (page + 1));
$.ajax({url: url, cache: true, async: true});
}),
error: (function(jqXHR, textStatus) {
})
});
>> What is full form of HMVC?
Hierarchical-Model-View-Controller. HMVC is an evolution of the MVC pattern.
>> What are benefits of HMVC?
Modularization
Organization
Reusability
Extendibility
>> How to check that Redis server is running?
try
{
$redis = \Redis::instance();
}
catch(\RedisException $e)
{
//here error will come
}
>> How To Create a New Table Using the MEMORY Storage Engine?
MEMORY storage engine stores table data in computer system memory. This is good for creating temporary tables.
>> Logicalquestion on mysql, If you have 2 tables with first record has 3 rows and second has 4 rows and your right bellow query then what will output?
Select t1.name, t2.description from tables1 as t1, table2 as t2;
//Output 12 rows
The out put will print 3X4 = 12 rows, it executes like first it will return first row of first table with all other rows in second table and then contine working row by row.
>> What is use of scop variable in angular js 1?
Scope is object which performs asssigning values to variable in controller so that user can use in particular controller with controller scope.
>> Write how to post/get request using curl?
>> What is NoSQL?
MongoDB
>> What is BIGData?
MongoDB
>> AngularJs
creating components and handling AJAX calls.
>> Apigee Edge
Apigee Edge is an advanced API platform that enables enterprises to create, manage, secure and scale APIs. Using Apigee, enterprises can design and deploy API proxies in public and private clouds, secure data in transit with OAuth 2.0, SAML and two-way TLS, protect against traffic spikes by adding dynamic routing, caching and rate-limiting policies to APIs, and measure the success of both API operations and API business with end-to-end analytics.
>> Which fatal errors are converted into exceptions in PHP 7?
--- >> in PHP 7 Throwable interface added. now use Throwable in try/catch blocks to catch both Exception and Error objects.
--- >> undefined function, required file missing, // are covered
--- >> uncaught exceptions, running outoff memory // are not covered
e.g.
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5
} catch (Exception $e) {
// Executed only in PHP 5, will not be reached in PHP 7
}
>> Calculate number of elements in array/multidimentional array?
sizeof, count function can be use.
We can use count, sizeof functions. for multidimentional array we can use count($arrayName, 1) or sizeof($arrayName, 1) with second parameter to 1.
>> What is Handler in php? What are PHP Handlers and Why Do They Matter?
- A PHP handler is what actually loads these coding libraries into the webserver, so that they can be interpreted. There are multiple handlers that can be used for loading PHP: CGI, DSO, suPHP, & FastCGI.
- Each handler delivers the libraries through different files and implementations.
- PHP handlers are necessary for everyday function of your server and determine how a PHP process is loaded on your server. To run PHP files or scripts on your site, a PHP handler is needed to decipher the code within a PHP file based on the PHP version to display the content over the web.
>> What kind’s of PHP Handler’s do we offer and support?
DSO
SuPHP
CGI
FCGI
>> How to calculate same/repeated values in array?
array_value_count($array) will return repeated value as key and repeat-count as value.
>> Database level
Oracle
MySql
SqlServe
MongoDB
Its internal mysql cache use to cache sql queries and result set internally so that we can get fast output for same query. The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again.
>> Is mysql case sensitive?
No, you can write mysql queries in various manners like SELECT, Select, select etc.
>>Explain how you can enable CSRF (Cross Site Request Forgery) in CodeIgniter?
$config['csrf_protection'] = TRUE;
>> Explain what are hooks in CodeIgniter
way to change the inner working of the framework without hacking the core files
$config['enable_hooks'] = TRUE;
>> security parameter for XSS(Cross side scripting) in CodeIgniter?
CodeIgniter has got a cross-site scripting hack prevention filter. This filter either runs automatically or you can run it as per item basis, to filter all POST and COOKIE data that come across. If it detects any suspicious thing or anything disallowed is encountered, it will convert the data to character entities.
>> what is inhibitor in CodeIgniter?
inhibitor is an error handler class, using the native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.
>> what is the default URL pattern used in CodeIgniter framework?
CodeIgniter framework URL has four main components in default URL pattern. First we have the server name and next we have the controller class name followed by controller function name and function parameters at the end. CodeIgniter can be accessed using the URL helper.
>> CodeIgnitor Architecture
Models
=> Routing => Security => Library
User || Application Controller Script
<= Cache <= View <= Plugins and Helpers
>> Differance between PHP 5 & PHP 7
PHP 7
1. Speed
Refactor the PHP codebase in order to reduce memory consumption and increase performance.
2. Type Declarations
. Scalar Type Hints
. Return Type Declarations
3. Error Handling
Most of the fatal error converted in to Exception error.
Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately stopping the script. An uncaught exception will also continue to be a fatal error in PHP 7
warnings and notices remain unchanged in PHP 7.
In PHP 7, Error and Exception both implement the new Throwable class. What that means is that they basically work the same way. And also, you can now use Throwable in try/catch blocks to catch both Exception and Error objects.
Virtually all errors in PHP 5 that were fatal, now throw instances of Error in PHP 7.
4. New Operators
. spaceship operator, or Combined Comparison Operator(<=>)
. Null Coalesce Operator ( $name = $firstName ?? "Guest"; )
1. Speed
Refactor the PHP codebase in order to reduce memory consumption and increase performance.
2. Type Declarations
. Scalar Type Hints
. Return Type Declarations
3. Error Handling
Most of the fatal error converted in to Exception error.
Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately stopping the script. An uncaught exception will also continue to be a fatal error in PHP 7
warnings and notices remain unchanged in PHP 7.
In PHP 7, Error and Exception both implement the new Throwable class. What that means is that they basically work the same way. And also, you can now use Throwable in try/catch blocks to catch both Exception and Error objects.
Virtually all errors in PHP 5 that were fatal, now throw instances of Error in PHP 7.
4. New Operators
. spaceship operator, or Combined Comparison Operator(<=>)
. Null Coalesce Operator ( $name = $firstName ?? "Guest"; )
>> What is difference between session and cookies?
In Session data store on server and Cookies data are store on client side.
Session data are more secure because they never travel on every http request and Cookies data are less secure because they travel with each and every HTTP request.
You can store objects in session (Store large amount of data) and you can store only string type of data in cookies (file size - 4kb).
Session cannot be used for future reference and Cookies are mostly used for future references.
>> The differences between the persistent cookie and temporary cookie are given below:
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
Temporary cookies cannot be used for tracking long-term information.
Persistent cookies can be used for tracking long-term information.
Temporary cookies are safer because no programs other than the browser can access them.
Persistent cookies are less secure because users can open cookie files see the cookie values.
>> What is SQL injection?
SQL injection attack occurs when a user provides SQL code as user input for a Web page, and the SQL code is then executed in the database.
Using prepared statement and parameterized queries we can prevent SQL injection.
$pdo = new PDO('mysql:hostname','databsename','user','psw');
$name = $_GET['name'];
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
foreach ($stmt as $row) {
// do something with $row
}
>> How session works after disabled cookie
Ans: Session works after disable cookies too. Server sends php session id into url on each requests.
>> What is difference between $ and this Jquery
Ans: $ is jQuery constructor and this is reference to DOM element
>> What are selectors in jQuery
Ans: Class, ID, tag/element, data attributes
>> What Is A Closure In PHP?
Ans: Closure is object representation of anonymous function. A class which(type) is used to represent anonymous function.
>> What are Design Pattern
Ans: Design patterns present useful ways for developing software faster.
>> Indexing.
We can use BTREE or HASH types to sort results in indexing.
table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data.
This is much faster than reading every row sequentially.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows.
MySQL uses indexes for these operations -
To find the rows matching a WHERE clause quickly.
To eliminate rows from consideration.If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows (the most selective index).
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows.
To retrieve rows from other tables when performing joins. MySQL can use indexes on columns more efficiently if they are declared as the same type and size.
To find the MIN() or MAX() value for a specific indexed column key_col.
To sort or group a table if the sorting or grouping is done on a leftmost prefix of a usable index.
B-Tree Index -
B-tree index can be used for column comparisons in expressions that use the =, >, >=, <, <=, or BETWEEN operators.
The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character.
The B-tree is a generalization of a binary search tree in that a node can have more than two children.
B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.
Hash Index -
They are used only for equality comparisons that use the = or <=> operators (but are very fast).
They are not used for comparison operators such as < that find a range of values.
The optimizer cannot use a hash index to speed up ORDER BY operations.
MySQL cannot determine approximately how many rows there are between two values.
Only whole keys can be used to search for a row. (With a B-tree index, any leftmost prefix of the key can be used to find rows.)
Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects.
e.g.
In universities, each student is assigned a unique roll number.
In libraries, each book is assigned a unique number.
>> If I don’t want to use session what is alternate option -
Best way to use the memcache for storing the data.
Also another option is to use database for storing the values.
HTML 5 local storage is one option.
Others include hidden fields and querystrings.
Application state might be another option.
Append data with the querystring (Passing data in querystring is not a good choice if those are secure and large. Also querystring too have it's own limit. So you can not pass data after certain limit.)
Securely Passing Identity Tokens Between Websites.
Encrypt and Decrypt URL in MVC 4.
secure query strings are limited to 2k after encryption.
browsers also limit index/local/session storage for mobile browsers its around 5mb. Localstorage you can go for if you do not want to process data on each and every request. As in that case you have to pass those data server side on each request.
e.g. store data in browser storage like local storage, session storage, cookie storage
function fnSaveData(){
window.localStorage.setItem(“CustName”,document.getElementById(“txtCustomer”).value);
window.localStorage.setItem(“CustAddr”,document.getElementById(“txtCustAddr”).value);
}
>> How to set default timezone on server side?
date.timezone = "UTC"; // php.ini
php_admin_value date.timezone "America/New_York" // VirtualHost
php_value date.timezone "America/New_York" // .htaccess
ini_set("date.timezone", "America/New_York"); // using php code
date_default_timezone_set('Asia/calcutta'); // using php code
>> When we get issue on server side then how can you trace that?
>> CI helper and types of helper, hooks. routes?
>> ubuntu
>> Create store procedure for flush records after 1000 records count?
Delimeter $$
create procedure proc_del_records()
begin
truncate table tbl;
end;
Delimeter $$;
Elayers Interactive private limited -
PHP how to add days, sec, min, hours in given strim date
>> strtotime('_2 days', ($givenStrim));
Display alert after all images load in document
>> $('window').load({})
Javascript how to get third input element?
>> document.querySelectorAll('input')[2]
how to check mysql current time zone?
>> SELECT @@global.time_zone, @@session.time_zone;
>> sfGuardPlugin -
The sfGuardPlugin is a symfony plugin that provides authentication and authorization features above the standard security feature of symfony.
It gives you the model (user, group and permission objects) and the modules (backend and frontend) to secure your symfony application in a minute in a configurable plugin.
Coding conventions(coding standards) are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language.
CDAC - Centre for Development of Advanced Computing.
Managed back-end and front-end development for this project, also I was responsible for client support after the project deployment.
Ans: Session works after disable cookies too. Server sends php session id into url on each requests.
>> What is difference between $ and this Jquery
Ans: $ is jQuery constructor and this is reference to DOM element
>> What are selectors in jQuery
Ans: Class, ID, tag/element, data attributes
>> What Is A Closure In PHP?
Ans: Closure is object representation of anonymous function. A class which(type) is used to represent anonymous function.
>> What are Design Pattern
Ans: Design patterns present useful ways for developing software faster.
>> Indexing.
We can use BTREE or HASH types to sort results in indexing.
table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data.
This is much faster than reading every row sequentially.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows.
MySQL uses indexes for these operations -
To find the rows matching a WHERE clause quickly.
To eliminate rows from consideration.If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows (the most selective index).
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows.
To retrieve rows from other tables when performing joins. MySQL can use indexes on columns more efficiently if they are declared as the same type and size.
To find the MIN() or MAX() value for a specific indexed column key_col.
To sort or group a table if the sorting or grouping is done on a leftmost prefix of a usable index.
B-Tree Index -
B-tree index can be used for column comparisons in expressions that use the =, >, >=, <, <=, or BETWEEN operators.
The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character.
The B-tree is a generalization of a binary search tree in that a node can have more than two children.
B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.
Hash Index -
They are used only for equality comparisons that use the = or <=> operators (but are very fast).
They are not used for comparison operators such as < that find a range of values.
The optimizer cannot use a hash index to speed up ORDER BY operations.
MySQL cannot determine approximately how many rows there are between two values.
Only whole keys can be used to search for a row. (With a B-tree index, any leftmost prefix of the key can be used to find rows.)
Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects.
e.g.
In universities, each student is assigned a unique roll number.
In libraries, each book is assigned a unique number.
>> If I don’t want to use session what is alternate option -
Best way to use the memcache for storing the data.
Also another option is to use database for storing the values.
HTML 5 local storage is one option.
Others include hidden fields and querystrings.
Application state might be another option.
Append data with the querystring (Passing data in querystring is not a good choice if those are secure and large. Also querystring too have it's own limit. So you can not pass data after certain limit.)
Securely Passing Identity Tokens Between Websites.
Encrypt and Decrypt URL in MVC 4.
secure query strings are limited to 2k after encryption.
browsers also limit index/local/session storage for mobile browsers its around 5mb. Localstorage you can go for if you do not want to process data on each and every request. As in that case you have to pass those data server side on each request.
e.g. store data in browser storage like local storage, session storage, cookie storage
function fnSaveData(){
window.localStorage.setItem(“CustName”,document.getElementById(“txtCustomer”).value);
window.localStorage.setItem(“CustAddr”,document.getElementById(“txtCustAddr”).value);
}
>> How to set default timezone on server side?
date.timezone = "UTC"; // php.ini
php_admin_value date.timezone "America/New_York" // VirtualHost
php_value date.timezone "America/New_York" // .htaccess
ini_set("date.timezone", "America/New_York"); // using php code
date_default_timezone_set('Asia/calcutta'); // using php code
>> When we get issue on server side then how can you trace that?
>> CI helper and types of helper, hooks. routes?
>> ubuntu
>> Create store procedure for flush records after 1000 records count?
Delimeter $$
create procedure proc_del_records()
begin
truncate table tbl;
end;
Delimeter $$;
Elayers Interactive private limited -
PHP how to add days, sec, min, hours in given strim date
>> strtotime('_2 days', ($givenStrim));
Display alert after all images load in document
>> $('window').load({})
Javascript how to get third input element?
>> document.querySelectorAll('input')[2]
how to check mysql current time zone?
>> SELECT @@global.time_zone, @@session.time_zone;
>> sfGuardPlugin -
The sfGuardPlugin is a symfony plugin that provides authentication and authorization features above the standard security feature of symfony.
It gives you the model (user, group and permission objects) and the modules (backend and frontend) to secure your symfony application in a minute in a configurable plugin.
Coding conventions(coding standards) are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language.
CDAC - Centre for Development of Advanced Computing.
Managed back-end and front-end development for this project, also I was responsible for client support after the project deployment.
Comments
Post a Comment