How to change controller and model directory path in codeigniter ?

Change controller and model directory path(in Codeigniter) –

You can changed it by using HMVC extension.
First of all download the extension code from –
https://github.com/skjain5793/codeigniter-modular-extensions-hmvc

Extract it and
i.) put /third_party  folder files in application/third_party folder
ii.) put /core folder files in application/core folder

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.

How to check that current page is a blog page in wordpress ?

Code to confirm that current page is a blog page in wordpress

Make a function in functions.php –
if(is_archive || is_author() || is_home() || is_single() || is_home() || is_tag() && post= ‘get_post_type’){
echo “this is a blog page”;
}

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.

Laravel Interview Questions 2020

Ques: What is artisan ?

Ans: Artisan is command-line interface that is used in laravel to develop an application. It provides some commands that may be helpful during development of an app.

Ques: What is composer ?

Ans: It is a dependency manager tool. Laravel also uses it to manage it’s dependencies.

Ques: What is middleware ?

Ans: As the name indicates, it acts as interface or middle layer between request and response. General example of middleware is authentication. If a user is authenticated then user will send to profile page otherwise, he/she will be redirected to login page.
There are 2 types of middleware in Laravel –
Global – It will run on every request.
Route – It will run with that route to which it is assigned.

Ques: What is dd() function ?

And: dd() stands for “Dump and Die”. It is Laravel’s helper function that can be used to dump the variable’s contents and to stop the further execution of script.

Ques: What are bundles ?

Ans: Bundles are packages that is a way to extend or add more functionality to Laravel.  These packages can have views, configuration, migrations, routes, and tasks which are mainly used to enhance the functionality.

Ques: Which database are supported by Laravel ?

Ans: Laravel supports the following databases:

– MySQL

– Postgres

– SQLite

– SQL Server

Ques: What is Lumen ?

Ans: It is a micro-framework of Laravel. It is smaller, faster an is a perfect solution for creating Laravel based  services and Restful APIs.

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.

Copy files to other server(ftp)

How to copy all files of a directory to a directory on other server ?
Suppose, we have to copy all files in a directory(dir/subdir) to other server directory(dir/sub) and we also have to create directory there(in case, if directory does not exist), then –

First of all make connection with Remote(other) FTP (from where we are copying the files) like –
$ftp_host = ‘host’;
$ftp_username = ‘ftp_username’;
$ftp_password = ‘ftp_password’;
$ftp_connection = ftp_connect($ftp_host);

Then, login to Remote or other ftp using –
$ftp_login = ftp_login($ftp_connection,$ftp_username,$ftp_password);

function isdir_ftp($ftp_connection,$dir){
$pushed = ftp_pwd($ftp_connection);
if($pushed!=false && @ftp_chdir($ftp_connection,$dir)){
ftp_chdir($ftp, $pushed);
return true;
}
return false;
}

Suppose, we have to copy the directory and files in public_html directory –
$server_path = “./public_html/”;
$file_path_server = “dir/subdir” ;
$server_file_path = $server_path. $file_path_server ;
$is_dir = isdir_ftp($ftp_connection, $file_path_server);
if(!$is_dir){
$dir = $file_path_server;
$dd = ”;
$d=explode(“,”,$dir);
for($i=0;$i<count($d);$i++){
$dd.=$d[$i].”/”;
//try to create dir
$dir = $dd;
$is_dir = isdir_ftp($ftp_connection, $dir);
if(!$is_dir){
if(ftp_mkdir($frp_connection, $dir)){
echo “Dir created successfully”;
}else{
echo “Error”;
}
}
}
}

Now read the files from local ftp from where we have to copy the files and the copy it –
$local_ftp_dir = ” dir/subdir “;
if ($handle = @opendir($ local_ftp_dir )) {
while (false !== ($file = readdir($handle))) {
if ($file != “.” && $file != “..”) {
$source= $ local_ftp_dir .’/’.$file;
$dest = “public_html/”.$ local_ftp_dir .’/’.$file;
$upload = ftp_put($ftp_connection, $dest, $source, FTP_BINARY);
if (!$upload) {
echo ‘FTP upload failed!’;
} else {
echo “uploaded successfully”;
}
}
}
}

ftp_close($ftp_connection);

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Copy files from other ftp or server to current ftp or server

Steps to copy all files of a particular folder from other ftp to current ftp –

First of all make connection with Remote(other) FTP (from where we are copying the files) like –
$ftp_host = ‘host’;
$ftp_username = ‘ftp_username’;
$ftp_password = ‘ftp_password’;
$ftp_connection = ftp_connect($ftp_host);

Then, login to Remote or other ftp using –
$ftp_login = ftp_login($ftp_connection,$ftp_username,$ftp_password);

After that get all files of that directory of remote ftp –
$remote_dir = ‘/dir/’;
$remote_files = ftp_nlist($ftp_connection,$remote_dir); //Array of all files from dir directory on remote server

Then, check that file exists in that directory on not –
if(count($remote_files)>0){ //There are files in remote server dir
foreach($remote_files as $remote_file){ //run loop through each file
$file_name = end(“/”,explode($remote_file)); //get file name from remote
$local_file = ‘local_dir/’.$file_name;
$server_file = $remote_file; //file from remote server
if(ftp_get($ftp_connection,$local_file,$server_file, FTP_ASCII)){
echo “File successfully copied”;
}else{
echo “error”;
}
}
}

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

PHP(Basic and OOPS) Interview Questions

Are you preparing for PHP Interview ? Whether you are a fresher or experienced, confidence is checked. Here are some questions for you ..

Ques: How to create object without class ?

Ans: You can create it by using empty class. You can use PHP stdClass (which is empty class in PHP) to create its object. It is useful if you are creating dynamic object or if you want to set some dynamic property.

For example –
$object = new stdClass();
$object->name = ‘test’;

Ques: What is armstrong number ? Write a program to check whether the number is armstrong or not.

Ans: Armstrong Number –
It is a number such that the sum of cube of each digit is equal to the number. For example – 153 is an armstrong number because sum of cube of each digit(1*1*1+5*5*5+3*3*3) is 153 which is same as number.

Program –
$n = 153; $sum = 0; $tmp = $n;
while($tmp!=0){
$rem = $tmp%10;
$sum = $sum+($rem*$rem*$rem);
$tmp=$tmp/10;
}
if($n==$sum) {
echo “It is armstrong number”;
}
else {
echo “Not an armstrong number”;
}

Ques: What is difference between object and array ?

Ans: Array is a collection of heterogeneous data(they may be with key value pair or without key value pair) and object is collection of key value pair.

Ques: What will be the output of following :
$a = 1;
foreach($a as $b){
echo $b;
}

Ans: It will give error because foreach works on Array not on string.

Ques: Write a program to find the missing number from an array of number from 1 to 99(There is not empty value if number is missing).
array(1,2,3,4,5,………..,99);

Ans: $array = array(1,2,3,4,5,……….,99);
for($i=0;$i<count($array)-1;$i++){
if($array[$i+1]!=$array[$i]+1){
$missing_number = $array[$i]+1;
echo “Missing Number is “.$missing_number;
}
}

Ques: Can we use session without cookies in PHP ?

Ans: Yes, in PHP, Session can be used without Cookies.
Way to use Session without Cookie –
There are two ways to do it –
1.) For a HTML form, PHP will add a hidden input whose name will be PHPSESSID. The value of PHPSESSID will be based on what PHP assigns to your session ID.
For Example –
<form>
<input type=”hidden” name=” PHPSESSID” value=”12345678″>
</form>
So, when form will be submitted, PHP will get Session id value from form and will get information about session.
2.) PHP will look for all links in HTML, and will modify them and will append PHPSESSID with them.
For Example –
<a href=”http:www.example.com”>Test</a>
PHP will change it to –
<a href=”http:www.example.com? PHPSESSID =12345678″>Test</a>

Ques: Write a program to show duplicate values in array and find the sum between duplicate values.
array(1,2,3,2,5,4,7,5,8).
Output – Duplicate Values are 2,5.
2+3+2 = 7
5+4+7+5 = 21

Ans:Program
$array = array(1,2,3,2,5,4,7,5,8);
$arr1 = array(); $arr2 = array();
for($i=0;$i<count($array);$i++){
if(in_array($array[$i],$arr1)){
$arr2[$i] = $array[$i];
}else{
$arr1[] = $array[$i];
}
}
echo “Duplicate Values are “.implode(“,”,$arr2);
echo “<br>”;

foreach($arr2 as $k=>$v){
$flag = 0;
for($i=0;$i<count($array);$i++){
if($array[$i]==$v && $flag==0){
$sum=0;
for($j=$i;$j<=$k;$j++){
$sum = $sum+$array[$j];
}
echo $sum;
echo “<br>”;
$flag = 1;
}
}
}

Ques: Write a program to check whether a number is palindrome or not.

Ans: Palindrome Number – Palindrome number is that number whose reverse is same as the number.
For Example – Number 131 is palindrome but number 57 is not palindrome.
Program –
$number = 131; $tmp = $number;
$rev = 0;
while(floor($tmp)){
$rem = $tmp%10;
$rev = $rev*10+$rem;
$tmp = $tmp/10;
}
if($number==$rev){
echo “Number is palindrome”;
} else{
echo “Number is not palindrome”;
}

Ques: Write a program to reverse an array at a position.
Array – array(1,2,3,4,5,6,7);
Position – 2
Output – array(4,5,6,7,1,2,3)

Ans: Program –
$array = array(1,2,3,4,5,6,7); $pos = 2;
for($i=0;$i<count($array);$i++){
if($i<=$pos){
$arr1[] = $array[$i];
}else{
$arr2[] = $array[$i];
}
}
$final_array = array_merge($arr2,$arr1);
echo implode(“,”,$final_array);

Ques: Write a program to print table of a number(say 8) without using loop.

Ans: Program –
$n = 8;
function print_table($n,$i){
if($i<=10){
echo $n*$i;
echo “<br>”;
return print_table($n,$i+1);
} else {
return;
}
}
print_table($n,1);

Ques: What is abstract function ?

Ans: It is the function that is defined but not implemented in the code.

Ques: How can i create the object if that class whose constructor is defined as private ?

Ans: You can not create object of that class. But if you have to use the function inside it then you should make function as static.
Example – 
Class Test(){
private function __construct(){
echo “constructor called”;
}
public static function display($message){
echo $message;
}
}

Test::display(‘Hello I am in the function’);

Ques: Write a program to find the sum of a matrix.
Matrix –     1  2  3  4
                  5  6  7  8
                  1  2  3  4
                  5  6  7  8

Ans:
function diagonalSums($matrix, $n)
{
$left_diagonal_sum = 0;
$right_diagonal_sum = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// principal diagonal
if ($i == $j){
$left_diagonal_sum += $matrix[$i][$j];
}

// secondary diagonal
if (($i + $j) == ($n – 1)){
$right_diagonal_sum += $matrix[$i][$j];
}
}
}

echo “Principal Diagonal: “.$left_diagonal_sum. “<br>”;
echo “Secondary Diagonal: “.$right_diagonal_sum.”<br>”;
}

$array = array (array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ),
array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ));
diagonalSums($array, 4);

Ques: Suppose there is an array with collection of objects, say
array(
    {
       ‘key’ : ‘1’,
       ‘name’ : ‘test’,
       ‘value’ : 1
   },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 2
  },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 3
  }
);

Print the object that is unique and if the objects key and name matches, then, their value is summed up and shown only once.

Output – 
array(
    {
       ‘key’ : ‘1’,
       ‘name’ : ‘test’,
       ‘value’ : 1
   },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 5(2+3)
  }
);

Ans:

$arr1 = array(“key”=>’1′, ‘name’ => ‘test’, ‘value’ => 1);
$obj1 = (object)$arr1;

$arr2 = array(“key”=>’2′, ‘name’ => ‘test2’, ‘value’ => 2);
$obj2 = (object)$arr2;

$arr3 = array(“key”=>’2′, ‘name’ => ‘test2’, ‘value’ => 3);
$obj3 = (object)$arr3;

$main_array = array($obj1, $obj2, $obj3);   //main array containing the objects

$final_array = array();

function search($key, $name, $array){
$response = array();
foreach($array as $k=>$v){
if($v->key==$key && $v->name==$name){
$response[0] = ‘1’;
$response[1] = $k;
break;
}else{
$response[0] = ‘0’;
$response[1] = ”;
}
}
return $response;
}

foreach($main_array as $main_key=>$main_value){
$res = search($main_value->key, $main_value->name, $final_array);
if(!empty($final_array) && $res[0]==1){
$final_array[$res[1]]->value = $final_array[$res[1]]->value+$main_value->value;
}else{
$final_array[] = $main_value;
}
}

echo “<pre>”;
print_r($final_array);

Ques: What is default session time in PHP ?

Ans: 24 minutes.

Ques: What is difference between unset() and unlink() ?

Ans: The unset() function will unset the variable i.e. it will make the variable undefined while the unlink() function is used to delete the files.

Ques: What is type casting ?

Ans: Changing the value from one format to another.
For example – There is an array and we have to convert it an object then –
Suppose – $array = array(“1″,”2”);
To convert it into object –
(object)$array;

Ques: What is difference between Abstraction and Interface ?

Ans: 1.) In abstraction, it is not necessary that all methods should be abstracted but in Interface every method should be abstracted.
2.) Interface methods should be public but abstraction methods can be public or protected.
3.) Inheritance supports both multiple and multilevel interface but abstraction supports single and multilevel inheritance.
4.) In interface, methods can only be defined. But in abstraction, methods can be defined as well as declared.

Ques: What is difference between PHP 5 and PHP 7 ?

Ans: 1.) Return Type – In PHP 7, type(float, int, other) of returning value can be defined.
For example – 
public function subtract(float $a, float $b) : float
{
return $a-$b;
}
2.) Null Coalesce Operator (??) – The coalesce operator(??) return result of its first operand if it exists or null.
For example – 
if(isset($_GET[‘id’])){
$id = $_GET[‘id’];
}else{
$id = null;
}
In PHP 7 –
$id = $_GET[‘id’]?? null;

Ques: What is PDO ?

Ans: PDO stands for PHP Data Objects. It is consitent interface to access database.

Ques: What is persistent cookie ?

Ans: Persistent cookies help to remember info., settings, preferences or login details. 
Persistent cookie have some expiration date.
Example – Google Analytics cookie is the best example of persistent cookie which tracks the visitors when they move through the website.

Ques: How to get the ip address of the client ?

Ans: $_SERVER[‘REMOTE_ADDR’] can be used to get that.

Ques: Write a program to check that a given string is palindrome or not without using second variable.

Ans: Program –
function palindrome($str){
   if(strlen($str)==0 || strlen($str)==1){
       return “It is palindrome”;
   }else{
      if(substr($str,0,1) == substr($str,(strlen($str)-1),1)){
         return palindrome(substr($str,1,(strlen($str)-2)));
     }else{
        return “It is not palindrome”;
     }
   }
}
$string = “NITIN”;
echo palindrome($string);

Ques: How will you reverse the words in a given string ?
Input – “garry’s giraffe gobbled goosberries greedily”
Output – “greedily goosberries goobled giraffe garry’s”

Ans: Program – 

$input = “garry’s giraffe gobbled goosberries greedily”;
$inputarray = explode(” “,$input);

$output = ”;

for($i=count($inputarray)-1;$i>=0;$i–){
$output.= ‘ ‘.$inputarray[$i];
}

echo $output;

Ques: Convert string into new string :
Input : abcD             
Output: cdeF

Ans: Program – 

$input = “abcD”;
$output = “”;

for($i=0; $i<strlen($input);$i++){
$ascii=ord($input[$i]);   //find ascii value of character
$output.= chr($ascii+2);   //add 2 to ascii value and then print character at that value
}

echo $output;

Ques: What is difference between array_merge() and array_combine() ?

Ans: array_merge() function merges the elements of the array in a single array.
For Example –
$array1 = array(1,”name”=>”Ram”);
$array2 = array(1,”position”=>”God”);
$final_array = array_merge($array,$array2);
When you print $final_array – print_r($final_array),
Output –
Array([0]=>1 [name]=>”Ram” [1]=>2 [position]=>”God”);

array_combine() function takes two array and creates the final array from them by using one array values as key and other array values as values of that keys.
$array1 = array(“name”,”position”);
$array2 = array(“Ram”,”God”);
$final_array = array_combine($array,$array2);
When you print $final_array – print_r($final_array),
Output –
Array([name]=>”Ram” [position]=>”God”);

Ques: What will the output of $x = true and false; var_dump($x) ?

Ans: true. In this, = takes precedence over and operator i.e. it becomes –
$x = true;  //set value of x to be true
true and false.  

Ques: What will be he output of –
$x = ‘php’; echo $x++;

Ans: php

Ques: Can we add third party site in our site in iframe or any code ?

Ans: No. There are server setting which the site owner can change that if site origin is their site then it will work. 

Ques: Difference between http and https.

Ans: 1.) Http uses port number 80 while https uses 443.
2.) Http works at Application layer while Https works at transport layer.
3.) In Http, Encryption is absent while in Https, encryption is present.

Ques: How to define constant in PHP ?

Ans: define is used to define constant.
define(“constant name”,”constant value”);

Ques: Write a program to print – 

***********
   *********
      *******
         *****
            ***
               *

Ans: $space = 0; $star = 11;
for($i=1; $i<=6; $i++){
for($j=1; $j<=$space+$star; $j++){
if($j<=$space){
echo ” “;
}else{
echo “*”;
}
}
echo “<br>”;
$space++; $star = $star-2;
}

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Get Last Level Category – WordPress

Function to get all last level category ( whether it is category or subcategory )which have posts iis as follows –

Do you want to get last level category in wordpress(whether it is category or subcategory) which have posts then create the custom function defined below and call it in all categories loop –

function return_lastpostcat($categories){
$categories_temp = $categories;
foreach ( $categories_temp as $child_cat ) {
foreach ( $categories_temp as $k => $parent_cat ) {
if ( isset( $categories[ $k ] ) ) {
if ( cat_is_ancestor_of( $parent_cat, $child_cat ) ) {
unset( $categories[ $k ] );
}
}
}
}
return $categories;
}

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Custom form validation Codeigniter

Some validation function are already defined in codeigniter form validation library. But sometimes, we might need to have a custom validation. You can do it by –

There are 2 ways to implement custom form validation in codeigniter

1.) Create function in controller (in the same controller in which we are implementing the validation).
2.) Create own or custom library and create function in that file.

1.) Create function in same controller –

Create function and call it by using callback_.

Example – Here is an example how to validate Indian mobile number using custom form validation function –

public function _check_phone($phone)

{

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

$this->form_validation->set_message(‘_check_phone’, ‘%s ‘.$phone.’ is invalid format’);

return false;

}

}

Function Call –

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|callback__check_phone’);

Disadvantage – You can use that function only that controller. What will you do if you have to put the validation at multiple places (controllers) ? So, its better to create custom library and create function in that library.

2.) Create Custom Library –

Create custom library file(say my_form_validation) in application/libraries directory.

Example – Same Indian mobile number validation –

<?php 

/**

 * CIMembership

 * 

 * @package Libraries

 * @author 1stcoder Team

 * @copyright   Copyright (c) 2015 1stcoder. (http://www.1stcoder.com)

 * @license http://opensource.org/licenses/MIT MIT License

 */

defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class MY_Form_validation extends CI_Form_validation 

{

protected $ci;

function __construct() {

parent::__construct();

$this->ci =& get_instance();

}

public function _check_phone($phone)

{

$this->ci->form_validation->set_message(‘_check_phone’, “This %s “.$phone.” is in invalid format!”);

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

return false;

}

}

}

Function Call –

 $this->load->library(‘my_form_validation’); //load the library

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|_check_phone’); // Call the functions like others

Note: You can create the function in both – controller and custom library But always prefer to write the function by creating custom library, so that in case, if need to use that function in multiple controllers, can be used easily.

 
 
 
____________________________________________
For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.

Codeigniter Interview Questions

I am sharing my personal exp. of interview. Prepare well before appearing in interview. Following is the list of questions that can be asked during the interview ..

Ques: How will you connect multiple databases in Codeigniter ?

Ans. In Application/Config/database.php –

Copy default database connection array and paste it and change database connection details and change the $db[‘default’] to $db[‘new_db’] in pasted array.

In model – 

public function __construct(){

parent::__construct();

$this->cipaypal_db = $this->load->database(‘new_db’,TRUE); 

/* $this->cipaypal_db = Variable Name and in $this->load->database(name) = should be same as $db[name] in database.php file */

}

Ques: What are logs in codeigniter ? What is the meaning of log status(0,1,2,3,4) ?

Ans. Logs are used for error handling. You can write your own message in it.

0 = Disables logging, Error logging TURNED OFF

1 = Error Messages (including PHP errors)

2 = Debug Messages

3 = Informational Messages

4 = All Messages

Ques: What are hooks ? Name all hooks.

Ans. Hooks are used to override the default functionality of codeigniter.

To enable hooks – 

$config[‘enable_hooks’] = TRUE;  /Application/config.php

There are 7 types of hooks available in codeigniter –

1.) pre_system

2.) pre_controller

3.) post_controller_constructor

4.) post_controller

5.) display_override

6.) cache_override

7.) post_system

Ques: Which protocol is used in Routing ?

Ans: Transmission Control Protocol (TCP).

Ques: How will you make database connection in routes in Codeigniter ? How will you define routing based on database value ?

Ans: require_once( BASEPATH .’database/DB.php’ );   //Include file

$db =& DB(); //Create instance of database

$query = $db->get( ‘table’ ); //Table for routing base on which routing will be done. 

$result = $query->result();

Ques: What are in inhibitors ?

Ans: It is a class that handles the error. It uses PHP native error handling functions like set_error_handler, get_exception_handler, register_shutdown_function to handle errors.

Ques: Where routing is defined in Codeigniter ?

Ans: In application/configuration/routes.php

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.