Saturday, October 27, 2018

phpMyPassion

Top PHP7 Interview Questions And Answers for Freshers & Experienced

This article shows up top frequently asked PHP7 interview questions and answers for PHP Developers, This list of PHP interview questions and answers will be helpful for PHP programmers.


Top PHP7 Interview Questions And Answers for Freshers & Experienced


Question #1 - How array_walk function works in PHP?


It is used to update the elements/index of original array.
How: in array_walk, two parameter are required. 
  1. original array
  2. An callback function, with use of we update the array. 
Question #2 - How to achieve Multilevel inheritance in PHP7?


//base class
class a{}

//parent class extend the base class
class bextends a{}

//chid class extend the parent class
class c extends b{}

Question #3 - 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 limit 1,1

Question #4 - require_once(), require(), include().What is difference between them?


require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Question #5 - What type of inheritance supports by PHP7?


There are following type of inheritance 

  • Single Inheritance - Support by PHP
  • Multiple Inheritance - Not support
  • Hierarchical Inheritance - Support by PHP
  • Multilevel Inheritance - Support by PHP
Question #6 - How do you call a constructor for a parent class?

parent::constructor($value);
Question #7 - How to find duplicate email records in users table?

SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
    SELECT email FROM users GROUP BY email HAVING count(id) > 1
    ) u2 ON u1.email = u2.email;

Question #8- What is the difference between Session and Cookie?
Both are used to store user information on server. The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can't hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
Question #9- How to pass data in header while using CURL?
$url='http://www.web-technology-experts-notes.in';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'headerKey: HeaderValue ',
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));
echo curl_exec($ch);
curl_close($ch);

Question #10 - What is Final Keyword in PHP7?

PHP7 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final keyword.
Question #11 - How can we prevent SQL-injection in PHP?


Sanitize the user data before Storing in database.
While displaying the data in browser Convert all applicable characters to HTML entities using htmlentities functions.
Question #12 - How to set header in CURL?

curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); 

Question #13 - What are different type of sorting functions in PHP7?

sort() - sort arrays in ascending order. 
asort() - sort associative arrays in ascending order, according to the value.
ksort() - sort associative arrays in ascending order, according to the key.
arsort() - sort associative arrays in descending order, according to the value.
rsort() - sort arrays in descending order.
krsort() - sort associative arrays in descending order, according to the key.
array_multisort() - sort the multi dimension array.
usort()- Sort the array using user defined function.

Question #14 - How to redirect https to http URL and vice versa in .htaccess?

Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Redirect http to https


RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Question #15 - What are benefits of .htaccess?

  • Routing the URL
  • Mange Error Pages for Better SEO
  • Redirection pages
  • Detect OS (like Mobile/Laptop/Ios/Android etc)
  • Set PHP Config variable
  • Set Environment variable
  • Allow/Deny visitors by IP Address
  • Password protection for File/Directory
  • Optimize Performance of website
  • Improve Site Security 

Question #16 - How we can retrieve the data in the result set of MySQL using PHP7?


  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_object()
  • mysqli_fetch_assoc()

Question #17 - What is the use of explode() function ?


This function is used to split a string into an array. Syntax : array explode( string $delimiter , string $string [, int $limit ] ); 
Question #18 - What is the difference between explode() and split() functions?


Split function splits string into array by regular expression. Explode splits a string into array by string.
Both function are used to breaks a string into an array, the difference is that Split() function breaks split string into an array by regular expression and explode() splits a string into an array by string. explode() is faster than split() because it does not match the string based on regular expression.  
Question #19 - What is the use of mysqli_real_escape_string() function?


mysqli_real_escape_string() function mainly used to escapes special characters in a string for use in an SQL statement
Question #20 - Write down the code for save an uploaded file in php.


if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
Question #21 - How to create a text file in php7?


$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
Question #22 - How to strip whitespace (or other characters) from the beginning and end of a string ?


We can use trim() function to remove whitespaces or other predefined characters from both sides of a string.
Question #23 - What is output of following?
$a = '10';
$b = &$a;

$b = "2$b";

echo $a;
echo $b;

Output


210
210

Question #24 - What are Traits?


Traits are a mechanism that allows you to create reusable code in PHP7 where multiple inheritance is not supported. To create a Traits we use keyword trait

Example of Traits
trait users {
    function getUserType() { }
    function getUserDescription() {  }
    function getUserDelete() {  }
}

class ezcReflectionMethod extends ReflectionMethod {
    use users;    
}

class ezcReflectionFunction extends ReflectionFunction {
    use users;
}

Question #25 - How to extend a class defined with Final?


No, You can't extend. A class declare with final keyword can't be extend.
Question #26 - What is full form of PSRs?

PHP Standards Recommendations. 
Question #27 - How do you execute a PHP script from the command line?


  • Get the php.exe path from server (My PHP path is : D:\wamp\bin\php\php5.5.12)
  • In environment variable, Add this path path under PATH variable.
  • Re-start the computer.
  • Now, you can execute php files from command file.
php index.php

Question #28 - What is stdClass in PHP7?


It is PHP7 generic empty class.
stdClass is used to create the new Object. For Example
$newObj = new stdClass();
$newObj->name='What is your name?';
$newObj->description='Tell me about yourself?';
$newObj->areYouInIndia=1;
print_r($newObj);

Output


stdClass Object
(
    [name] => What is your name?
    [description] => Tell me about yourself?
    [areYouInIndia] => 1
)

Question #29 - How to start displaying errors in PHP7 application ?

Add following code in PHP.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

OR
Add following code in .htacess


php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on

Question #30 - What are different type of errors?


E_ERROR: A fatal error that causes script termination.
E_WARNING: Run-time warning that does not cause script termination.
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code.
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup.
E_CORE_WARNING: Warnings that occur during PHP's initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error 
E_ALL: Catches all errors and warnings 

Question #31 - When to use self over $this?

Use $this to refer to the current object.
Use self to refer to the current class.

Example of use of $this


class MyClass1 {
    private $nonStaticMember = 'nonStaticMember  member Called.';        
    
    public function funcName() {
        return $this->nonStaticMember;
    }
}

$classObj = new MyClass1();
echo $classObj->funcName();//nonStaticMember  member Called.


Example of use of SELF


class MyClass2 {
    private static $staticMember = 'staticMember  member Called.';        
    
    public function funcName() {
        return self::$staticMember;
    }
}

$classObj = new MyClass2();
echo $classObj->funcName(); //staticMember  member Called.

Read More

Wednesday, August 8, 2018

phpMyPassion

PHP Program To Find Odd Even Number

Find Odd Even Number || PHPMYPASSION

"Find odd even number " is the basic PHP program for a PHP learner. As you all aware, Odd numbers are not divisible by 2 and Even numbers are divisible by 2. 

Example :
    Odd number: 3, 5, 7, 9,11
    Even number: 2, 4, 6, 8, 10 

So here I am gonna explain it with a simple PHP program.

Odd Even Number Program :-


<?php

$number=22;

if($number%2==0)
{
 echo "22 is an even number"; 
}
else
{
 echo "22 is not odd number";
} 

?>

Output :-

22 is an even number


You can also do this by defining a PHP function to check a number is odd or even as below -



PHP function to check odd even number :-


<?php
function checkOddEven($num)
{
   if($num%2==0)
   {
     $result = "Even number"; 
   }
   else
   {
     $result = "Odd number";
   }
   retrun $result;
}

echo checkOddEven(43);
?>

Output :-

Odd number
Read More

Tuesday, August 7, 2018

phpMyPassion

Swap Two Number Program In PHP

Swap Two Numbers Program || PhpMyPassion

Swap two number generally is the process of interchange two variables with each other. Just suppose you have X whose value 10 there is another number Y with value of 20. Now if we swap these two number with each other then the X value will change to 20 and Y  value will change to 10.

So here I am gonna explain with a simple PHP program.

Swap Two Number Program :-


<?php

$x=10;
$y=20;

echo "Value of x: $x</br>";
echo "Value of y: $y</br>";

$temp=$x;
$x=$y;
$y=$temp;

echo "Value of x: $x</br>";
echo "Value of y: $y</br>";

?>

Output :-

Value of x: 10
Value of y: 20
Value of x: 20
Value of y: 10


You can also do this by without using third variable as below -

Swap Two Number Without Using Third Variable Program :-


<?php

$x=10;
$y=20;

echo "Value of x: $x</br>";
echo "Value of y: $y</br>";

$x=$x+$y;
$y=$x-$y;
$x=$x-$y;

echo "Value of x: $x</br>";
echo "Value of y: $y</br>";

?>

Output :-

Value of x: 10
Value of y: 20
Value of x: 20
Value of y: 10

Read More

Monday, August 6, 2018

phpMyPassion

Armstrong Number Program in PHP

PhpMyPassion
"Armstrong Number Program" is the initial program from where most of the beginner developers will start to learn and write code in any language. An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits is equal to the number itself.
Here is an example of check a armstrong number in PHP.

Armstrong Number Program :-

Below is the simple PHP program to check a number armstrong.

<?php

$number=153;
$sum=0;
$temp=$number;
while($temp!=0)
{
$reminder=$temp%10;
$sum=$sum+$reminder*$reminder*$reminder;
$temp=$temp/10;
}
if($number==$sum)
{
echo "It is an Armstrong number";
}
else
{
echo "It is not an armstrong number";
}

?>

Output :-

It is an Armstrong number
Read More

Saturday, August 4, 2018

phpMyPassion

Process to Install Docker on Ubuntu 16.04

Process To Install Docker || PhpMyPassion

Docker :-

Docker is a container management service. The keywords of Docker are develop, ship and run anywhere. The whole idea of Docker is for developers to easily develop applications, ship them into containers which can then be deployed at anyplace.

Docker has two flavors :

  • Community Edition (CE)
  • Enterprise Edition (EE)

So if you don't know which one should be install, just pick up The Community Edition (CE) flavor and install as below 

Docker Installation :-

Follow the step by step process -

Step#1 :- Set up the docker repository

$ sudo apt-get update
$ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Step#2 :- Install Docker CE
$ sudo apt-get update
$ sudo apt-get install docker-ce

Step#3 :- Verify the installation
$ sudo docker run hello-denny

So above process will help you to install Docker on Linux environment. If you found any difficultly, do follow the Ubuntu installation instruction list all you need in detail.  

Know More About Docker:

      What is docker and uses ? 

Read More

Thursday, August 2, 2018

phpMyPassion

What is Docker and Why We Use ?

Docker Introduction || PhpMyPassion

What is docker ?
Docker is a container management service. The keywords of Docker are develop, ship and run anywhere. The whole idea of Docker is for developers to easily develop applications, ship them into containers which can then be deployed at anyplace.
Docker has two flavors : The Community Edition (CE) and the Enterprise Edition (EE)
Initial Release : March 2013
Mostly use on agile based project.
Why docker ?
  • Docker has the ability to reduce the size of development by providing a smaller footprint of the operating system via containers.
  • With containers, it becomes easier for teams across different units, such as development, QA and Operations to work seamlessly across applications.
  • You can deploy Docker containers anywhere, on any physical and virtual machines and even on the cloud.
  • Since Docker containers are pretty lightweight, they are very easily scalable.
For more details : why docker
Docker Terms :
Docker Engine : "Docker engine" is the part of Docker which creates and runs Docker containers.
Docker Hub : SaaS service for sharing and managing application stacks.
( Docker Hub is a registry service on the cloud that allows you to download Docker images that are built by other communities. You can also upload your own Docker built images to Docker hub )
Docker Compose : Docker Compose is a tool for defining and running multi-container Docker applications. It uses Yaml files to configure the application's services and performs the creation and start-up process of all the containers with a single command.
Using Compose, it is basically a three-step process.
  1. Define your app's environment with a Dockerfile so it can be reproduced at anyplace.
  2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
  3. In the end, run docker-compose up and Compose will start and run your entire app.
For more information read: Docker compose
Docker Image: There everything is based on Images.
Docker file: The Dockerfile is essentially the build instructions to build the image.
For more details : Docker file
Docker-compose.yml : Config. Application’s services.

More About Docker:

Read More

Sunday, July 22, 2018

phpMyPassion

How To Set Custom Variables With DataLayer in GoogleTag manager (GTM) ?

Google Tag Manager DataLayer || PhpMyPassion

The most common problem for GTM is to setting up custom variables with dataLayer and make that dynamic for your JavaScrip tag.

So here I am gonna explain it with an article. follow whole process for setting up custom variables for your custom JavaScript tag.

I have already explained about GTM or its overview in my one of article. You can read that overview of google tag manager here

Setting Up Custom Variable With DataLayer :


To setting up custom variables with dataLayer, developers has to pass the variables from their code.

for an example :

just suppose your JS-SDK required data like eventName & jsonPayload and other parameters as below. 

<script>
var _pmp = _pmp || [];
var cb = Math.random()*10000000000000000;
!function(m,d,e,v,n,t,s)
{if(m.pmp)return;n=m.pmp=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!m._pmp)m._pmp=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=d.createElement(e);t.async=!0;
t.src=v;s=d.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window,document,'script',
'js/trackmyscript.js?cb='+cb);
_pmp.push(['init','PMP-XXX']);
_pmp.push(['dataTrack', 0, 'event-NAME', {jsonPayload}]); //parameters to e pass
</script>

You can set the datalayer to pass these variables from your code as below-

if your conversion event is of SignUp, then you have to setup dataLayer from your server side script as below-

Conversion Event : dataTrack_cnv

<script>dataLayer.push("event":"dataTrack_cnv", "eventName":"Buying", "jsonPayload":"{"md_prid":"p1234", "md_prname":"myProduct", "cur":"usd"}")</script>

You can also set this dataLayer on Ajax Response & on button click.
make sure you have initialise dataLayer object before the GTM-Tag as below - 
<head>
<!-- Google Tag Manager -->
<script>
var dataLayer = [];
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXX');
</script>
<!-- End Google Tag Manager -->
</head>

Now its time to create dataLayer variable by that we can pass it to our JS-SDK-TAG. 

Process to use dataLayer variables in your custom JS-SDK gtm tag :-

To use these variables you have to create variables in GTM as below -

Setting up DataLayer variable in gtm || PhpMyPassion

  • First give a name to your variable like - eventName, jsonPayload etc.
  • Now choose variable type to "Data Layer Variable" because we are already set dataLayer variables from code.
It will looks like below screen after choosing Data Layer variable -


Here eventName below DataLyer variable is the already above set DataLayer variabel name.
  • Now click to save and use your variable into your created JS-SDK tag in gtm -

<script>
var _pmp = _pmp || [];
var cb = Math.random()*10000000000000000;
!function(m,d,e,v,n,t,s)
{if(m.pmp)return;n=m.pmp=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!m._pmp)m._pmp=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=d.createElement(e);t.async=!0;
t.src=v;s=d.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window,document,'script',
'js/trackmyscript.js?cb='+cb);
_pmp.push(['init','PMP-XXX']);
_pmp.push(['dataTrack', 0, {{eventName}}, {jsonPayload}]); //parameters to e pass
</script>








  • Now set trigger to all pages



      • Publish your container tag and start to track your event.
      So using the whole process developers can set dataLayer variable in their website code and pass to GTM JS-SDK-TAG accordingly. Google Tag Manager makes it more easy to track event with a little bit changes in your website.

      If anybody found the issue in setting up dataLayer variables from their website or in passing to GTM, can comment here. I will always here for helping you. 


      More About Google Tag Manager (GTM):

      Read More