Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Configuring Virtual Hosts in XAMPP on Mac OS X

Configuring virtual hosts in xampp on mac is not an easy task.  It has some extra work to do as compared to windows or linux. Here is all the steps to configure it on mac.

STEP 1: open terminal and type

            vim /etc/hosts

It will open hosts file in vim editor (of course you can choose nano or others). press  i  and it will be in insert mode. Then add your host entry such as

127.0.0.1         localhost
127.0.0.1         localhost.zend.com

STEP 2:   Now you need to open

/Applications/XAMPP/xamppfiles/etc/httpd.conf 

(xampp installation path) either in vim or in normal editor via finder (file system in mac). Now you have to find this line

# Include /Applications/XAMPP/etc/extra/httpd-vhosts.conf

and need to remove # from starting i.e. uncomment it. save and close this file.

STEP 3: Now you need to open file
/Applications/XAMPP/xamppfiles/etc/extra/httpd-vhosts.conf 

and need to add set up your directory and host relation but before that make sure this line

NameVirtualHost *:80

is added before you add your settings. Like this-

NameVirtualHost *:80
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin webmaster@localhost.com
    DocumentRoot "/Applications/XAMPP/xamppfiles/htdocs"
    ServerName  localhost
    ServerAlias www.localhost.com
    ErrorLog "logs/localhost-error_log"
    CustomLog "logs/localhost-access_log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost.ci34.com
    DocumentRoot "/Applications/XAMPP/xamppfiles/htdocs/ci34"
    ServerName  localhost.ci34.com
    ServerAlias www.localhost.ci34.com
    ErrorLog "logs/localhost.ci34.com-error_log"
    CustomLog "logs/localhost.ci34.com-access_log" common
</VirtualHost>

STEP 4: You are almost done just need to restart apache from xampp panel. That's it. Your site is now ready to be used as localhost.ci34.com (whatever you added in hosts & httpd-vhosts.conf file).

Interview Questions and Answers

Abstract class vs Interface

An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();

int getFuel();
}

// my team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{

int fuel;

void run()
{
print("Wrroooooooom");
}


int getFuel()
{
return this.fuel;
}
}

Abstract Class- Abstract classes are those classes which can not be directly initialized. Or in other word we can say that you can not create object of abstract classes. Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract.


// I say all motor vehicles should look like this :
abstract class MotorVehicle
{

int fuel;

// they ALL have fuel, so why not let others implement this?
// let's make it for everybody
int getFuel()
{
return this.fuel;
}

// that can be very different, force them to provide their
// implementation
abstract void run();


}

// my team mate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("hurrr");
}
}


The key technical differences between an abstract class and an interface are:

  • Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
  • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  • When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.
  • Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  • A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

MySQL Cluster

MySQL Cluster is a technology providing shared-nothing clustering and auto-sharding for the MySQL database management system. It is designed to provide high availability and high throughput with low latency, while allowing for near linear scalability.[2]MySQL Cluster is implemented through the NDB or NDBCLUSTER storage engine for MySQL ("NDB" stands for Network Database).

MySQL Cluster is designed around a distributed, multi-master ACID compliant architecture with no single point of failure. MySQL Cluster uses automatic sharding (partitioning) to scale out read and write operations on commodity hardware and can be accessed via SQL and Non-SQL (NoSQL) APIs

Database Index

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.

Indexes are also type of tables, which keep primary key or index field and a pointer to each record into the actual table.

The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.

INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to insert or update index values as well.

Unique Key

A unique index means that two rows cannot have the same index value.
Syntax -

CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
 
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) 

Primary Key

A primary key uniquely identify a row in the table. A table can have only one Primary Key.
Syntax-
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list)

Full Text Index

FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause.
Synatx-
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list)

Method Overriding vs Method Overloading



Exporting data from mysql to excel with phpExcel multi sheets

What is phpExcel?


It is a library which enables to to create excel sheets and csv via pure php. phpExcel is very popular for that purpose.

How to create excel sheet from database?

How to create multi sheet excel file using php?


<?php
 require_once 'Classes/PHPExcel.php';
 require_once 'Classes/PHPExcel/IOFactory.php';

 require_once("codelibrary/inc/variables.php");//to connect to database and some core functions

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("RN Kushwaha")
->setLastModifiedBy("Aryan")
->setTitle("Reports")
->setSubject("Excel Turorials")
->setDescription("Test document ")
->setKeywords("phpExcel")
->setCategory("Test file");
 
// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Name');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Email');
$objPHPExcel->getActiveSheet()->setCellValue('D1', 'Phone');

$n=2;
$qry= mysql_query("select * from tbl_agent ");
while($d= mysql_fetch_array($qry)){
$objPHPExcel->getActiveSheet()->setCellValue('A'.$n, $d['id']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$n, $d['name']);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$n, $d['email']);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$n, $d['contact_no']);
   $n++;
}                
                
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Agents');

// Create a new worksheet, after the default sheet
$objPHPExcel->createSheet();

// Add some data to the second sheet, resembling some different data types
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Title');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Email');
$objPHPExcel->getActiveSheet()->setCellValue('D1', 'Phone No');

$n=2;
$qry=executeQuery("select * from tbl_technician ");
while($d= mysql_fetch_array($qry)){
$objPHPExcel->getActiveSheet()->setCellValue('A'.$n, $d['id']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$n, $d['title']);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$n, $d['email']);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$n, $d['phone']);
$n++;
}       

// Rename 2nd sheet
$objPHPExcel->getActiveSheet()->setTitle('Technician');

// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="data.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

this will create an excel file data.xlsx with two worksheets `agents` and `technicians` and downloads it.

Download a csv file from database.

To download a csv file you can change something like this as csv does not support multiple worksheets.


<?php
require_once 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
require_once("codelibrary/inc/variables.php");

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("RN Kushwaha")
->setLastModifiedBy("Aryan")
->setTitle("Reports")
->setSubject("CSV Download")
->setDescription("Test document ")
->setKeywords("phpExcel")
->setCategory("Test file");
 
// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Name');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Email');
$objPHPExcel->getActiveSheet()->setCellValue('D1', 'Phone');

$n=2;
$qry=executeQuery("select * from tbl_agent ");
while($d= mysql_fetch_array($qry)){
$objPHPExcel->getActiveSheet()->setCellValue('A'.$n, $d['id']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$n, $d['name']);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$n, $d['email']);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$n, $d['contact_no']);
  $n++;
}                
                
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Agents');
header("Content-Disposition: attachment; filename='data.csv' ");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save('php://output');

This will download a csv file.
Note: In this tutorial mysql_* functions are used just for simplicity to understand beginners. In actual you should use pdo or mysqli.

Using cURL to get a page

What is cURL?


cURL is a library that can be used to connect and communicate with different types of servers with different types of protocols. It supports http, https, ftp, gopher, telnet, dict, file, and ldap protocols. It also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, and user+password authentication.

First of all it needs to initialize;

$ch= curl_init();
then use curl_setopt() for single value and curl_setopt_array() to set multiple options.
then use curl_exec();
in last use curl_close();

How to get a page's content using cURL?


function getURLData( $url ){
        $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
        $options = array(
            CURLOPT_CUSTOMREQUEST  => "GET",         // set request type post or get
            CURLOPT_POST           => false,         // set to GET
            CURLOPT_USERAGENT      => $user_agent,   // set user agent
            CURLOPT_RETURNTRANSFER => true,          // don't output just return web page content
            CURLOPT_SSL_VERIFYPEER => false,         // don't exit on ssl check
            CURLOPT_HEADER         => false,         // don't return headers
            CURLOPT_FOLLOWLOCATION => true,          // follow redirects
            CURLOPT_ENCODING       => "",            // handle all encodings
            CURLOPT_AUTOREFERER    => true,          // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,           // timeout in sec on connect
            CURLOPT_TIMEOUT        => 120,           // timeout in sec on response
            CURLOPT_MAXREDIRS      => 10,            // stop after 10 redirects
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );//comment if you don't want info about download size,
//       header size, request_size,size_download etc
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }

Usage:-

    $result= getURLData("http://www.google.com/search?q=post+data+with+get+curl+php");
    //print_r($result);
    if ( $result['errno'] != 0 ){
      if ( $result['http_code'] != 200 ){
         echo $page = $result['content'];
      }else echo $result['errmsg'];
   } else echo $result['errmsg'];


How to login using cURL? How to post form data using cURL?



function curlPost($url,$postData){
$ch= curl_init();
curl_setopt_array($ch, array(
   CURLOPT_URL => $url,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_POST => true,
   CURLOPT_POSTFIELDS => $postData,
   CURLOPT_FOLLOWLOCATION => true,
   CURLOPT_CONNECTTIMEOUT=>30,
   CURLOPT_SSL_VERIFYPEER=>false,
   CURLOPT_USERAGENT=>"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
   CURLOPT_COOKIESESSION => true,
   CURLOPT_COOKIEFILE => 'cookie.txt',
   CURLOPT_COOKIEJAR => 'cookie.txt'
));
$output = curl_exec($ch);
curl_close( $ch );
return $output;
}

Usage:

$postData = array(
   '_method' => 'POST',
   'email' => 'aryan022@gmail.com',
   'password' => 'aryan022',
   'redirect_to' => 'http://localhost/cakephp/account ',
   'testcookie' => '1'
);
$output=curlPost("http://localhost/cakephp/login",$postData);

/*use for subsequest request without passing all postData
  $postData = array();
  $output=curlPost("http://localhost/cakephp/account",$postData);
*/

echo $output;