Showing posts with label PHP Language. Show all posts
Showing posts with label PHP Language. Show all posts

Tuesday, 11 January 2022

PHP Interview Questions

 PHP Questions and Answers

1.PHP tool used to send SMS to users when a form is filled and submitted. Give simple snippet.


//API URL

$url="https://control.msg91.com/sendhttp.php";

 

// init the resource

$ch = curl_init();

curl_setopt_array($ch, array(

    CURLOPT_URL => $url,

    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_POST => true,

    CURLOPT_POSTFIELDS => $postData

    //,CURLOPT_FOLLOWLOCATION => true

));

 

 

//Ignore SSL certificate verification

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

 

 

//get response

$output = curl_exec($ch);

//Print error if any

if(curl_errno($ch))

{

     echo 'error:' . curl_error($ch);

}

 

curl_close($ch);

}


2. What is CRUD in PHP.  Give simple snippet.


Create = INSERT or Create New Table

Read = SELECT

Update = UPDATE

Delete = DELETE

Query for insert Data into table

"Insert into (table_name) values(value1,value2,value3......)"

Insert into tbl_Student values(1,'Manish');

Insert into tbl_Student values(2,'Rahul');

Query for (Select or Read) Data into table


"select * from table_Name "

select * from tbl_Student

Query for Update Data of table


UPDATE table_Name SET column1=value1,column2=value2,... WHERE some_column=some_value;

UPDATE tbl_Student SET StudentName='Gyan' WHERE StudentName='Manish';

Query for Delete Data from table


" Delete from table_Name"

delete from tbl_student where StudentId=1;

3. Where CRUL is used in real time scenarios?


curl is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP). The command is designed to work without user interaction.


To retrieve the example.com homepage on command line interface.

FTP upload

User authentication

Check the city from which the user is visiting your website

Get remote file size

4. MVC concept in codeigniter


A Design Pattern.  Stands for Model, View and Controller. Separate Business Logic from Presentation Logic

5. PHP snippet to create JSON data. This will come handy when you are creating web services for mobile apps.


$json_data = array ('id'=>1,'name'=>"Mohit");

echo json_encode($json_data);


6. To store data, you would need a database. Give sample snippet using MySQL database.Using basic Procedural PHP method and OOPS in PHP method.


<?php

$connect = @mysql_connect($mysql_host, $mysql_user, $mysql_password)or die(mysql_error());

$db = @mysql_select_db($mysql_database,$connect)or die(mysql_error());

?>

<?php

$con = @mysqli_connect("$dbhost","$dbusername","$dbpassword","$dbname");

?>


Original MySQL API is deprecated Instead, the -------------------or ------------------ extension should be used. 

mysqli_connect()

PDO::__construct()


7.How to upload a file asynchronously and store it. Provide ajax snippet.


$.ajax({

url: "ajax_php_file.php", // Url to which the request is send

type: "POST",             // Type of request to be send, called as method

data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)

contentType: false,       // The content type used when sending data to the server.

cache: false,             // To unable request pages to be cached

processData:false,        // To send DOMDocument or non processed data file it is set to false

success: function(data)   // A function to be called if request succeeds

{

$('#loading').hide();

$("#message").html(data);

}

});


$sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable

$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored

move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file


<body>

<div class="main">

<h1>Ajax Image Upload</h1><br/>

<hr>

<form id="uploadimage" action="" method="post" enctype="multipart/form-data">

<div id="image_preview"><img id="previewing" src="noimage.png" /></div>

<hr id="line">

<div id="selectImage">

<label>Select Your Image</label><br/>

<input type="file" name="file" id="file" required />

<input type="submit" value="Upload" class="submit" />

</div>

</form>

</div>

<h4 id='loading' >loading..</h4>

<div id="message"></div>

</body>


8. How to read a csv file.


function readCSV($csvFile){

$file_handle = fopen($csvFile, 'r');

while (!feof($file_handle) ) {

$line_of_text[] = fgetcsv($file_handle, 1024);

}

fclose($file_handle);

return $line_of_text;

}

<?php

$csvFile = "test.csv";

$csv = readCSV($csvFile);

$a = csv[0][0]; // This will get value of Column 1 & Row 1

?>


9. Parsing Json Data


$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';

$obj=json_decode($json_string);

//print the parsed data

echo $obj->name; //displays rolf

echo $obj->office[0]; //displays google

10. Download image from url


function imagefromURL($image,$rename)

{

$ch = curl_init($image);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);

$rawdata=curl_exec ($ch);

curl_close ($ch);


$fp = fopen("$rename",'w');

fwrite($fp, $rawdata); 

fclose($fp);

}

<?php

$url = "http://koonk.com/images/logo.png";

$rename = "koonk.png";

imagefromURL($url,$rename);

?>

11. Convert HTML to PDF in PHP with -------------- Library


Dompdf

12. Pdf to image converter with -------------- Library 


ImageMagick

13. Difference b/w mail() and phpmailer()


The mail() function requires a local mail server to send out emails. PHPMailer can use a non-local mail server (SMTP) if you have authentication.

Sending an E-Mail with Attachments

14. What is composer?


Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries.

15. Real difference between REST and CRUD


CRUD means the basic operations to be done in a data repository. You directly handle records or data objects; apart from these operations, the records are passive entities. Typically it's just database tables and records.

REST, on the other hand, operates on resource representations, each one identified by an URL. These are typically not data objects, but complex objects abstractions.

For example, a resource can be a user's comment. That means not only a record in a 'comment' table, but also its relationships with the 'user' resource, the post that comments, maybe another comment that it answers.

Operating on the comment isn't a primitive database operation, it can have significant side effects, like firing an alert to the original poster, or recalculating some gamelike 'points', or updating some 'followers stream'.

Also, a resource representation includes hypertext (check the HATEOAS principle), allowing the designer to express relationships between resources, or guiding the REST client in an operation's workflow.

In short, CRUD is a set primitive operations (mostly for databases and static data storages), while REST is a very-high-level API style (mostly for webservices and other 'live' systems).

The first one manipulates data, the other interacts with a working system.

16. What Is Referential Integrity? - Definition & Examples


Referential integrity is a property of data which, when satisfied, requires every value of one attribute (column) of a relation (table) to exist as a value of another attribute (column) in a different (or the same) relation (table).

Consider the situation where we have two tables: Employees and Managers. The Employees table has a foreign key attribute entitled ManagedBy which points to the record for that employee’s manager in the Managers table. Referential integrity enforces the following three rules:

We may not add a record to the Employees table unless the ManagedBy attribute points to a valid record in the Managers table.

If the primary key for a record in the Managers table changes, all corresponding records in the Employees table must be modified using a cascading update.

If a record in the Managers table is deleted, all corresponding records in the Employees table must be deleted using a cascading delete.


17. PHP Namespaces


PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Avoid Name collisions between code you create, and internal PHP classes/functions way of encapsulating items

18. Blowfish encryption with example to store the password using crypt and compare the password using crypt. Other commonly used encryption methods are?


if(crypt($password_entered, $password_hash) == $password_hash) { // password is correct }

Advanced Encryption Standard Algorithm

Data Encryption standard algorithm

19. What is MD5? Is md5 decryption possible


md5 is a hashing technique. You cannot decrypt it back.Hashing means, once you are converted it to a encrypted code, you cannot go back! But you can still compare the md5 encrypted value with the another md5 encrypted value to check matches (mostly in the case of password verification and all!)

The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number.

20. Retrieve only a portion of an array. Example: in 1,2,3,4,5 retrieve 3,4 using array function.


$limited_array = array_chunk($my_array,10);print_r($limited_array);


PHP Language

Role & Responsibilities of Person looking for job in PHP

  • 5+ year’s professional development experience with Linux, Nginx, Apache, MySQL, PHP (object oriented), JavaScript, AJAX, JSON and XML.
  • Provide technical leadership for development teams.
  • Deep functional knowledge and hands on design experience with Web Services (REST, SOAP, etc ..).
  • Hands on design & development skills in HTML5, CSS, SaSS, LESS.
  • Proficiency designing and building APIs using PHP
  • PHP MVC Framework experience – Symfony / Laravel
  • Demonstrated ability with HTML5/CSS, javaScript (Angular/NodeJS), JSON/XML
  • Should have experience with Joomla, WordPress, Drupal, Magento.
  • Knowledge of caching types (MEMCache, REDIS, CDN)
  • Working knowledge on building Node or Python based applications.
  • Knowledge in any one of JavaScript frameworks like angularJS, emberJS, backbone JS, ReactJS etc. frameworks and openness to work on any of these frameworks.
  • Firm grasp of Git-based source control
  • Familiarity with automated deployment strategies
  • Familiarity with software design patterns
  • Strong in MySQL and NoSQL databases
  • Experience in eCommerce
  • Experience with caching and scaling techniques
  • Experience with CSS preprocessors like SASS/LESS
  • Experience with Twitter BootStrap framework
  • Good understanding on AWS, Google Cloud or Azure is a huge plus
  • Knowledge on DevOps work like Amazon Web Services, Google Cloud is a huge plus.
  • Basic knowledge on how Docker works.
  • Basic knowledge on CI/CD tools like Jenkins, Travis, AnthillPro, etc.
  • Basic knowledge on CDN like Akamai.
  • Excellent verbal and written communication skills.