Thursday, 16 March 2017

CakePHP Interview Questions and Answers for fresher + experienced

Here we’ll discuss about some basic and advanced cakephp interview questions and answers which are most ask-able questions during interview session, These CakePHP questions and answers will help you to crack CakePHP technical interview round.

Question: What is Cakephp?

CakePHP is a free, open-source, MVC (Model, View, Controller) rapid development framework for PHP. It’s a framework which help you to make development fast and secure. CakePHP goal is to enable developers to work in a structured and rapid manner–without loss of flexibility.


Question: What is MVC in CakePHP?

Model view controller (MVC) is an architectural pattern used in software engineering.
Model: Handle database related functionality, manipulating database related query like add, edit , delete.
View: Design parts written here (HTML+PHP)
Controller: Business Logic goes here

Question: What Is The Name Of Cakephp Database Configuration File Name And Its Location?

FileName: database.php.default
Location: /app/config/database.php.default

Question: What is First cakphpe file loaded in application?

bootstrap.php


Question: What is the folder structure of CakePHP?

cakephp/
app/
Config/
Console/
Controller/
Lib/
  Locale/
  Model/
  Plugin/
  Test/
  tmp/
  Vendor/
  View/
  webroot/
    .htaccess
  index.php

 lib/
 plugins/
 vendors/
 .htaccess/
 index.php/
 README.md/

Question:What Is The Use Of Security.Salt And Security.CipherSeed In Cakephp?

The Security.salt is used for generating hashes.
The Security.cipherseed is used for encrypt/decrypt strings.

Question: What is default function for a controller?

function index() is default function in controller.


Question:Which function is executed before every action in the controller?

function beforeFilter()

Question: What Is Scaffolding In Cakephp?

Scaffolding is a technical way that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

Question: List some of the features in CakePHP?

* MVC architecture
* In-Built validations
* Caching
* Scaffolding
* CSRF protection via Security Component.
* Access Control Lists and Authentication and creating role management system.

Question: How to add Scaffolding in your application?

By adding $scaffold variable in the controller see following example.

<?php
class PostsController extends AppController {
    var $scaffold;
}
?>

Question: How To Include Components In Controller?


echo $this->here;

Question: How To Get Controller Name In CakePHP Views?

$this->request->params['controller']


Question: How To Get Controller Action Name In CakePHP Views?

$this->request->params['action']

Question: Which Methods Are Used To bind And Destroy Model Associations?

bindModel() : used to bind Model Associations
unbindModel() : used to destroy Model Associations

Question: What Is The Default Extension Of view files In Cakephp?

.ctp

Question: What is a Helper in CakePHP?

Helpers in CakePHP are associated with Presentation layers of application.Helpers mainly contain presentational logic which is available to share between many views, elements, or layouts

Question:What is a Behavior in CakePHP?

Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.

Question: What is the difference between Component, Helper, Behavior?

Component is a Controller extension, Helpers are View extensions, Behavior is a Model Extension.

Question: How to set variables for views?

$this->set('name','Cake PHP');

Question: How to set layout for controller

By adding $layout variable in the controller see following example.

<?php
class PostsController extends AppController {
    public $layout = 'layoutname';
}
?>

Setting layout for particular action,

layout = ‘layoutname’;
}
}
?>

Question: How to write, read and delete the Session in cakephp?

$this->Session->write(‘User.name’, ‘Rohit Kumar’);
$black = $this->Session->read(‘User.name’);
$this->Session->delete(‘User’);

Wednesday, 8 March 2017

How to import excel file into mysql using php

With the help of php we can easily import our excel or csv file data in our Mysql database.
So i am going to show you some methods doing this easily

How to import excel file into mysql using php

To import excel data into php-mysql records first create a table with required fields. Make database connection. Open excel file and read columns one by one and store in variables.


Method-1: Import excel data using php script

$handle = fopen("BooksList.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
echo "<br>";
}


Method-2:

$handle = fopen("BooksList.csv", "r");
$fields=array('category','datatype','date','value');
$table='test';
$sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
           $rows[] = implode(",",$data);
  }
$sql_query .= implode("),(", $rows);
$sql_query .= ")";
echo $sql_query;


Method:3 Using third party library like php-excel-reader

Download form http://code.google.com/p/php-excel-reader/downloads/list

require_once 'Excel/reader.php'; 
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('BooksList.xls');
for ($x = 2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    echo "<br>";
 }

Hope this will help you to import your excel file into mysql db.
Thanks :)

Tuesday, 7 March 2017

How to upload file in cakephp without refersh page

Change image without refresh page in php and jquery, Upload file without refresh page in cakephp and jquery


Here we are going discuss about how to upload image or file without refresh page in cakephp and jquery.

Create controller in cakephp

ProfilesController.php

class ProfilesController extends AppController {
var $name = 'Profiles';
public $uses = array('Profile');
function changeprofilephoto() {
$profile_id = “14”; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Profile->set( $this->data );
$name = $this->data["Profile"]['profile_pic']['name'];
$size = $this->data["Profile"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Profile"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Profile->set($this->data);
$this->Profile->id=$profile_id;
$this->Profile->saveField('uploadfoldername',$actual_image_name);
echo "<img src='/profilepic/".$actual_image_name."' class='preview'>";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
}


Create view file

Views/Profiles/changeprofilephoto.ctp

 <?php
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>

<script type="text/javascript" >
$(document).ready(function() {
$('#profile_pic').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image
$("#Profile").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<div class="layout-popup f-left">
<?php
echo $this->Form->create('Profile',array('id'=>'Profile', 'controller'=>'Profiles','action'=>'changeprofilephoto', 'type'=>'file'));
?>


<!-- start id-form -->
<table class="frm-tbl" id="id-form" >
<tr>
<td colspan="2" class="align-t-r" >
<div class="f-left popup-title">Change profile image</div>
</td>
</tr>
<tr>
<td>Upload your image</td>
<td align="left" >
<!-- <input type="file" name="[Profile][photoimg]" id="profile_pic" /> -->
<?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
</td>
</tr>
<tr>
<td colspan="2">
<div id='preview'>
</div>
</td>
</tr>
</table>
<?php
echo $this->Form->end();
?>
</div>

Thanks cheers :)

Monday, 6 March 2017

How to create dynamic XML sitemap and submit to google web master for indexing


In this tutorial I’ll tell you very important method to generate dynamic xml sitemap for your website and how can we indexed all our dynamic url in google search.

Every body wants to create website now days and generate some traffic fast. So this is the trick for smart geeks, The below script is tested by me and worked great for me.

Let me tell you my experience, I had aprox 2 lakh dynamic urls which i created from my database rocords and i want to index all urls in google search, So i have created a php script which pull records from database and create a dynamic url for each records.

Suppose we have a books table with their name and auther.

ID NAME                 AUTHOR
1 Book Name-1 Book Author-1
2 Book Name-2 Book Author-2
3 Book Name-3 Book Author-3

My task is to index all my books url with their author name in google search, so that if anybody is looking for same books then he can find me in google search. Google automatically crawl urls but if you want fast result then give it try.

Create file sitemap.php and paste below script after that upload your sitemap.php file in your project root directory, Your sitemap url will be http://www.example.com/sitemap.php

You can make changes in below script according to your need this is just for demonstration purpose.

sitemap.php

<?php
  header('Content-type: application/xml');
  $baseurl = "http://example.com/books/";
  $hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "booksdb";
$con = mysqli_connect($hostname, $username, $password, $dbname);

 function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

  $output = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
  echo $output;
?>
  <?php $query = "SELECT name, author, id FROM books WHERE  status=1 LIMIT 0, 50000";
    $result = mysqli_query($con, $query);
    $res = array();

    while($resultSet = mysqli_fetch_assoc($result)) { 

 if(!empty($resultSet['name'])) { ?>

<url>
  <loc><?php echo $baseurl.clean(trim($resultSet['name'])).'/'. clean(trim($resultSet['author'])).'/'.$resultSet['id']; ?></loc>
</url>
<?php }  } ?>
</urlset>

Now time to submit your xml sitemap to google web master.

Login into your google web master account and submit your site map.


How to create dynamic XML sitemap and submit to google web master for indexing


If you don’t know how to submit sitemap in google web master please follow this tutorial.




Sunday, 5 March 2017

How to make visible newly hosted websites in google search

How to make visible newly hosted websites in google search

Today we are going to discuss about a very important issue we face while we purchase and host our newly website and facing the issue with google search that why my website is not showing in google search.

SO here i am going to discuss about my experience what i do with my website to index in google search and got visibility in next 24-48 hours.


My steps to index my wordpress blog in google search super fast.

Note: Before doing below steps your website should be live.

Step-1: Create google webmaster account.

https://www.google.co.in/webmasters/

Steps-2: Create XML sitemap for your website and if you have normal html website there is lot’s of online XML sitemap generater tools are available on web like https://www.xml-sitemaps.com/

If your website in wordpress you can install some available plugins for generating XML sitemap for your website.

I used “Yoast” one of the best plugin for doing SEO of wordpress website. And generate XML Sitemap.

Step-3: Place your website XML sitemap on your web root directory using ftp if you used online XML sitemap generater tools.

Your sitemap map url look like www.yourWebsiteName.com/sitemap.xml
In case of wordpress YOAST it does this task automatically.

Step-4: Login into your google web master account and add your website by click on “ADD A PROPERTY” button and popup will open here add your website link and click on continue button.

Step-5: Now click on your added website you can add multiple website here. you’ll see the dashboard. Now click on crawl-> sitemaps in left panel and here you’ll see ADD/TEST SITEMAP button on top right corner.

Step-6: create robots.txt file and place this file in your website root directory via ftp.

What is robots.txt

robots.txt tells search engines which pages have to index and which are not.
You can read more about robots.txt from here http://www.robotstxt.org/

My robots.txt is

User-agent: *
Disallow: /wp-admin/

Where Disallow means i don’t want to crawl my admin panel in google search.

After creating robots.txt file place this file in your website root directory and check it
www.yourWebsiteName.com/robots.txt
Or use google web master robots.txt tester tool.

Now wait at least 24-48 hours your website will become start indexing in google search, You can check by this syntax in google search box

site:yourWebsiteName.com


Hope this tutorial will help you to index your website fast in google search.


Thursday, 2 March 2017

How to Quickly Extract Domain Name & it’s components from URL in PHP


In this quick tutorial, I am going to show you How to Quickly Extract Domain Name & it’s components from URL in PHP, In some cases of development you need to extract host name and it’s parameter individually, For parsing domain name you can simply use php parse_url function to extract domain name, It’ll not only return domain but also Parse the whole URL and return its components in associative array format.

See example below

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
var_dump(parse_url($url));

OutPut:

array(4) { ["scheme"]=> string(4) "http" ["host"]=> string(15) "html-css-designing-tips.blogspot.com" ["path"]=> string(13) "/page/" ["query"]=> string(15) "id=1&name=php" }

Extract Domain Name

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
$result = parse_url($url);
echo $result['host']; // output: html-css-designing-tips.blogspot.com


How to parse XML in PHP – simpleXML

How to parse XML in PHP – simpleXML

Many websites on internet like to share their feed in XML format so that other website owner can show that feed on his/her website / blog. In PHP there is a function called simpleXML can simplify the process of reading the feeds into something useful for your web pages.

If You have wordpress installed in your server you can also on Rss feed of your blog and share your news/ articles with other websites. this will increase your blog visibility and good for SEO also.
See tutorial: Read RSS feed of website (blog) using php


Here is sample xml file.

companydb.xml

<?xml version='1.0'?>
<companydb>
  <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</phone>
  </company>
    <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</phone>
  </company>
</companydb>


With simpleXML, it’s as easy reading the XML file and then accessing it’s contents by an easy to read object. Suppose we have our XML file above saved as a file called comopanydb.xml with all the company details in the same folder as our php file, we can read the whole xml feed by following php function.

 $companydb = simplexml_load_file('companydb.xml');

Now we have created file object, go next for accessing it’s content. like if you want to display the name of the all companies then use below code.

<?php
    $companydb = simplexml_load_file('companydb.xml');
    foreach ($companydb as $company) {
        echo $title=$company->name." - ".$company->city." - ".$company->phone."<br/>";      
  } 
?>

Above is the quick example for parsing xaml data in php, you can store you data in xml file and access with this method.

Wednesday, 1 March 2017

How to create custom component in cakephp

How to create custom component in cakephp



In this tutorial we are going to write our own hello world component (plugin) in CakePHP.

The component is a logic container in CakePHP (ex. plugin in WordPress). All just needed is, include it and utilize those functions in that component. If some CakePHP developers want share their programming logic or functionality with fellow CakePHP developers, they will write as a component and share it with their programming community.

Once your Cakephp installation, database connections and security salt setting everything done. We are now able write our first hello world CakePHP component.


Step 1:

I am going to create component in the name of muni i.e. MuniComponent

To create your CakePHP component all you needed is to create php file in the follwoing directory. That’s app/controller/component/MuniComponent.php

Every component class we are creating must extends base component class that’s in the CakePHP library folder (lib/Cake/Controller/Component.php). So first in the component import component class.

App::uses('Component', 'Controller');

Where Controller – Indicates folder name
Component — Indicates class name we are including in the file.


Now create Component class, and write hello() function that returns ‘hello world’ string.

<?php 

App::uses('Component', 'Controller');

class MuniComponent extends Component {

    // hello world function
public function hello() {
return 'hello world';
}
}

?>

That’s it you successfully created your first hello world compnont in CakePHP, so any one use your component in their application .i.e. controller.

Step 2:


Now we are going to use the componenet(MuniComponent) just we written now. So I am going use this component in my UsersController. Before use any component in a controller, we must include it in a controller.

public $components = array('Muni');

Now I am going use hello() function of the component in the Controller, which going to return ‘hello world’ string.

<?php

App::uses('Controller', 'Controller');

class UsersController extends Controller{

//include component you want to use
public $components = array('Muni');

public function index()
{
$this->layout = 'common';
//calling component function we written
$data = $this->Muni->hello();
$this->set( 'data', $data);
}
}
?>


I have added one more function in the MuniComponent, that’s passwordGenerator() function which going to return random password when we are going to call it.

// password generator function
public function passwordGenerator( $length = 10){
    $letters ="@#$%^&*()_-+<>':,.1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return substr(str_shuffle($letters), 0, $length);
}

In controller

//calling password generator function of component
$pass = $this->Muni->passwordGenerator(20);
$this->set( 'pass', $pass);

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...