Showing posts with label Zend Framework. Show all posts
Showing posts with label Zend Framework. Show all posts

Monday 27 October 2014

Zend Gdata Youtube API - Search Video - View Video Detail

Zend Gdata Youtube API - Search Video - View Video Detail

Youtube API is very useful to show the youtube videos in your website. You don't required any account for search the video. You can filter the video by query string, category, limit no of records & you can see even video detail.
You can also upload OR do changes in uploaded videos but for this you need youtube account.On the behalf of my experience I am presenting some easy example which let you understand the youtube API. These example are testing with zend framework 1.12. Please let me your thoughts on this...



Search Videos by Category
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->category = 'Comedy/dog';
//$query->setCategory('Comedy/dog'); OR 
$videos = $yt->getVideoFeed($query);
$this->printVideoFeed($videos);


Search Videos by query string
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->videoQuery = 'dogs';
$videos = $yt->getVideoFeed($query);
$this->printVideoFeed($videos);


List Top Rated Videos
$yt = new Zend_Gdata_YouTube();
$videos = $yt->getTopRatedVideoFeed();
$this->printVideoFeed($videos);


List Today's Top Rated Videos
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setTime('today');
$videos = $yt->getVideoFeed($query);
$this->printVideoFeed($videos);


List videos by viewCount & Add limit
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->orderBy = 'viewCount';
$query->startIndex = 10;
$query->maxResults = 20;
$videos = $yt->getVideoFeed($query);
$this->printVideoFeed($videos);



Example In Zend Framework 
class IndexController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {

        // action body
    }

    function printVideoFeed($videoFeed) {
        foreach ($videoFeed as $videoEntry) {
            $this->printVideoEntry($videoEntry);
        }
    }

    function printVideoEntry($videoEntry) {
        echo '\n Video: ' . $videoEntry->getVideoTitle();
        echo '\n Video ID: ' . $videoEntry->getVideoId();
        echo '\n Updated: ' . $videoEntry->getUpdated();
        echo '\n Description: ' . $videoEntry->getVideoDescription();
        echo '\n Category: ' . $videoEntry->getVideoCategory();
        echo '\n Tags: ' . implode(", ", $videoEntry->getVideoTags());
        echo '\n Watch page: ' . $videoEntry->getVideoWatchPageUrl();
        echo '\n Flash Player Url: ' . $videoEntry->getFlashPlayerUrl();
        echo '\n Duration: ' . $videoEntry->getVideoDuration();
        echo '\n View count: ' . $videoEntry->getVideoViewCount();
        echo '\n Rating: ' . $videoEntry->getVideoRatingInfo();
        echo '\n Geo Location: ' . $videoEntry->getVideoGeoLocation();
        echo '\n Recorded on: ' . $videoEntry->getVideoRecorded();

        foreach ($videoEntry->mediaGroup->content as $content) {
            if ($content->type === "video/3gpp") {
                echo '
 Mobile RTSP link: ' . $content->url;
            }            
        }
        echo "\n\n";
    }

    function youtubeAction() {
        $yt = new Zend_Gdata_YouTube();
        $query = $yt->newVideoQuery();
        $query->category = 'Comedy/dog';
        //$query->setCategory('Comedy/dog'); OR 
        $videos = $yt->getVideoFeed($query);
        $this->printVideoFeed($videos);
        die("");
    }

}

Execute:/index/youtube


Output:
Video: My 200th Video
Video ID: h23oPnh1WJM
Updated: 2014-10-27T00:30:41.000Z
Description: Please subscribe to my channel and my vlog channel! I make new videos here every Wednesday and make vlogs during my majestical daily life. JennaMarbles Jenna...
Category: Comedy
Tags:
Watch page: https://www.youtube.com/watch?v=h23oPnh1WJM&feature=youtube_gdata_player
Flash Player Url: https://www.youtube.com/v/h23oPnh1WJM?version=3&f=videos&app=youtube_gdata
Duration: 263
View count: 3640139
Rating: Array
Geo Location:
Recorded on:
Mobile RTSP link: rtsp://r6---sn-p5qlsu76.c.youtube.com/CiILENy73wIaGQmTWHV4PuhthxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
Mobile RTSP link: rtsp://r6---sn-p5qlsu76.c.youtube.com/CiILENy73wIaGQmTWHV4PuhthxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp



Friday 10 October 2014

Download Videos from Amazon S3 - PHP

Download Videos from Amazon S3 - PHP

            $newFileName = "download_filename.mp4";
            header('Content-Type: video/mp4');
            header('Content-Disposition: attachment; filename="' . $newFileName . '"');
            $my_aws_key = 'AWS_KEY';
            $my_aws_secret_key = 'AWS_SCRET_KEY';
            $s3 = new Zend_Service_Amazon_S3($my_aws_key, $my_aws_secret_key);
            $newFileName = "S3_download_filename.mp4";
            $response = $s3->getObjectStream("$newFileName");//download stream from s3
            readfile($response->getStreamName());
            

How to set Cron in Zend Framework?

How to set Cron in Zend Framework?

Step 1: Don't execute bootstrap's run function directly in index.php
File Location: public_html/index.php
Update Following code:
if (php_sapi_name() != 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
 $application->bootstrap()->run();
}


Step 2: Create a folder cronjob in web application root folder.


Step 3. Create a file init.php under cronjob folder and add following code.
// Define path to application directory
defined('APPLICATION_PATH')
        || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
        || define('APPLICATION_ENV', 'environment');

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
            realpath(APPLICATION_PATH . '/../library'),
            get_include_path(),
        )));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
                APPLICATION_ENV,
                APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();



Step 4: Create a file mycron.php under cronjob folder.
Add following code in mycron.php
require_once 'init.php';
print_r($_SERVER);


Step 5. Append following code in mycron.php.
Now, you can access all models like below
$obj = new Application_Model_Logs();
In this file you can access zend's all global variable even you can access all models files with same way you had used in controller.

Step 6: Now Test the cron with following command
Login to putty and go to folder where your PHP is installed and run following code.
php C:\wamp\www\myproject\cronjob\mycron.php 




Tuesday 23 September 2014

Zend Cache Tutorial - Zend Framework 1.12

Zend Cache Tutorial - Zend Framework 1.12

Zend_Cache provides a flexible approach toward caching data, including support for tagging, manipulating, iterating, and removing data.

Question: What is Zend Cache?
It is Inbuilt component of zend framework which is used to speed up the application by using the caching concept.


Question: Why we use Zend Cache?
We use Zend cache for different purpose are following
  • Increase the website Performance.
  • Reduce the load on database.
  • Reduce the load of api, if using in application.
  • To get the result faster.


What is the use of  Zend Cache?
We can speedup our application as well as can reduce the burdon on database and API.
Zend_Cache use the file system to store the cache. We have option in zend cache to use the other caching component like Memcached, Sqlite, ibmemcached,Apc,Xcache and ZendPlatform etc. In this tutorial we will understand the zend_cache with file system.


How to Setup Zend Cache?
Step1: Add Following function Bootstrap
    public function _initCache() {
        $cache = Zend_Cache::factory(
                        'Core', 'File', array(
                    'lifetime' => 3600 * 24 * 7, /*caching time is 7 days*/                            
                    'automatic_serialization' => true
                        ), array('cache_dir' => APPLICATION_PATH . '/cache' /* This is caching folder where caching data will be stored and it must be writable by apache **/
                    )
        );
       
        Zend_Registry::set('Cache', $cache); /* set the cache object in zend_registery so that you can globally access*/
    }
Step2: cache folder must be writeable by PHP
Step3: Now, Just use the zend cache
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey);
        }





What is Tagging in Zend Cache?
Tags are a way to categorize cache records. You can add two OR more type of records in single tag. You can create unlimited tags and also can add unlimited records in single tag.


How to used Tagging in Zend Cache.
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey , array('Tags'));
        }


Can we add multiple Tags for 1 Record?
Yes, We can do.
$cache->save($result, $cacheKey , array('Tag1','Tag2','Tag3')); 


How can we clean one cache?
$cache->remove('idToRemove');


How to clean all records?
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);


How to clean outdated records?
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);


How to clean all records of one/more tags?
$cache->clean(
    Zend_Cache::CLEANING_MODE_MATCHING_TAG,
    array('Tag1', 'Tag2')
);

Wednesday 3 September 2014

Zend Framework Interview Questions and Answers for Experienced

Zend Framework Interview Questions and Answers for Experienced


Question: How to disable layout from controller?
$this->_helper->layout()->disableLayout();


Disable Zend Layout from controller for Ajax call only
if($this->getRequest()->isXmlHttpRequest()){
    $this->_helper->layout()->disableLayout(); 
}


How to change the View render file from controller?
function listAction(){
    //call another view file file
    $this->render("anotherViewFile");
}

How to protect your site from sql injection in zend when using select query?
$select = $this->select()                
                ->from(array('u' => 'users'), array('id', 'username'))
                ->where('name like ?',"%php%")
                ->where('user_id=?','5')
                ->where('rating<=?',10);



How to check post method in zend framework?
if($this->getRequest()->isPost()){
    //Post
}else{
//Not post
}


How to get all POST data?
$this->getRequest()->getPost();

How to get all GET data?
$this->getRequest()->getParams();


How to redirect to another page from controller?
$this->_redirect('/users/login');


How to get variable's value from get?
$id= $this->getRequest()->getParam('id');


Create Model file in zend framework?
class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = "users";
    protected $_primary = "id";      
}


How to create object of Model?
$userObj = new Application_Model_Users();


Which Class extend the Zend Controller?
Zend_Controller_Action
For Example
class AjaxController extends Zend_Controller_Action {
}


Which Class extend the zend Model?
Zend_Db_Table_Abstract
For Example
class Application_Model_Users extends Zend_Db_Table_Abstract { } 


What is a framework?
In software development, a framework is a defined support structure in which another software project can be organized and developed.


Why should we use framework?
Framework is a structured system where we get following things
Rapid application development(RAD).
Source codes become more manageable.
Easy to extend features.


Where we set configuration in zend framework?
We set the config in application.ini which is located in application/configs/application.ini.


What is Front Controller?
It used Front Controller pattern. zend also use singleton pattern.
=> routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
=> routeShutdown: This function is called after the router finishes routing the request.
=> dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
=> preDispatch: called before an action is dispatched by the dispatcher.
=> postDispatch: is called after an action is dispatched by the dispatcher.


What is full form of CLA in Zend Framework?
Contributor License Agreement


Should I sign an individual CLA or a corporate CLA?
If you are contributing code as an individual- and not as part of your job at a company- you should sign the individual CLA. If you are contributing code as part of your responsibilities as an employee at a company, you should submit a corporate CLA with the names of all co-workers that you foresee contributing to the project.



How to include js from controller and view in Zend?
From within a view file: $this->headScript()->appendFile('filename.js'); From within a controller: $this->view->headScript()->appendFile('filename.js'); And then somewhere in your layout you need to echo out your headScript object: $this->headScript();


What are Naming Convention for PHP File?
1. There should not any PHP closing tag (?>)in controller & Model file.
2. Indentation should consist of 4 spaces. Tabs are not allowed.
3. The target line length is 80 characters, The maximum length of any line of PHP code is 120 characters.
4. Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character. Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A


What are Naming Convention for Classes, Interfaces, FileNames, Functions, Methods, Variables and constants?
http://framework.zend.com/manual/1.11/en/coding-standard.naming-conventions.html


What are coding style of Zend Framework?
http://framework.zend.com/manual/1.12/en/coding-standard.coding-style.html


What is Front Controller in Zend Framework?
Zend used Front Controller pattern for rendering the data. It also use singleton pattern.
=> routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
=> routeShutdown: This function is called after the router finishes routing the request.
=> dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
=> preDispatch: called before an action is dispatched by the dispatcher.
=> postDispatch: is called after an action is dispatched by the dispatcher.

How to use update statemnet in Zend Framework?
  class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = 'users';
    protected $_primary = 'id';
 
    function updateData($updateData = array()) {
        //please update dynamic data
        $this->update(array('name' => 'arun', 'type' => 'user'), array('id=?' => 10));
    }
}


How we can do multiple column ordering in Zend Framework?
  class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = 'users';
    protected $_primary = 'id';
 
    function users() {
        $select = $this->select()
        ->setIntegrityCheck(false)
        ->from(array('u' => 'users'), array('name as t_name'))->order('first_name asc')->order('last_name des');
         return $this->fetchAll($select);
    }
 
}

Tuesday 15 July 2014

Zend Framework Interview Questions and Answers

Question: What is a framework?
In software development, a framework is a defined structure in which we can developed a new project. Its better to developed in framework than in core technology Because when we get a easy setup and many inbuilt functionalities.


Question: What are the features of framework?
Feature of Framework An abstract design Set of common functionality inbuilt Fast & Reliable Already tested by 1000 of developers We can check the reviews & rating of framework before use


Question: How to get post/get variables?
getRequest();
$request->getParams(); //All Get Variables
$request->getPost();//all Post variables
$request->getParam('id','0'); //get Id variables

Question: What is Bootstrapping?
Many PHP applications funnel server requests into a single PHP source file (only php files) that sets up the environment and configuration for the application, manages sessions, manage translate and caching, and invokes the dispatcher for their MVC framework. They can do more, but their main job is to take care of the consistent needs of every page of a web application.


Question: What is Zend Engine?
Zend Engine is used internally by PHP as a complier and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes. this opcodes render the html files.


Question: How Zend Routing Works?
Zend_Controller_Router_Rewrite is the standard router for zend framework. Basically Routing is the process of taking a URI endpoint and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a Zend_Controller_Request_Http object which is then processed by Zend_Controller_Dispatcher_Standard. Routing occurs once, when the request is initially received and before the first controller is dispatched.


Question: What are Plugins in zend framework?
Plugins are triggered by front controller events,bookend each major process of the front controller and allow automating actions that apply globally.
routeStartup – before the current route is evaluated
routeShutdown – after the completion of routing
dispatchLoopStartup – before the dispatch loop is entered
preDispatch – before the current action is dispatched
postDispatch – after the current action is dispatched
dispatchLoopShutdown – after the dispatch loop is completed


Question: How to disable Layout?
$this->_helper->layout()->disableLayout();


Question: How to disable view files?
$this->_helper->viewRenderer->setNoRender(true);


Question: How to call two different views from same action?
$this->render('differentView.phtml');


Question: How to include css from controller and view in zend framework.
From View
$this->headLink()->appendStylesheet('filename.css')
From Controller
$this->view->headLink()->appendStylesheet('filename.css');


Question: What is FrontController?
It is based on Front Controller Design pattern. Zend also use singleton pattern.
routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
routeShutdown: This function is called after the router finishes routing the request.
dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
preDispatch: called before an action is dispatched by the dispatcher.
postDispatch: is called after an action is dispatched by the dispatcher.

Friday 16 May 2014

Zend Framework - Free Google Analytics API

Zend Framework - Free Google Analytics API

After making a successful website, we add an  google analytics code to track the activities on our website. It gives all tracking information from all geo regions on all the pages.
It help us to know daily, monthly, yearly visiter in different countries and list of pages which searched most.

But creating a report on the behalf of analytics data, is difficult stuff because it take a lot of lot of time.

Following are simplest way to get the google analytics data.
        $email = 'ADSENSE_GMAIL_USERNAME';
        $password = 'ADSENSE_GMAIL_PASSWORD';
        /** Get Connection with Analytics Account * */
        $client = Zend_Gdata_ClientLogin::getHttpClient($email, $password, Zend_Gdata_Analytics::AUTH_SERVICE_NAME);
        $service = new Zend_Gdata_Analytics($client);
        /** Get Connection with Analytics Account * */
        
        
        /** Get Analytics Account Information * */        
        $profileResults = $service->getDataFeed($service->newAccountQuery()->profiles())->current()->getExtensionElements();
        foreach($profileResults as $profileResult){
            $attributes = $profileResult->getExtensionAttributes();
            $name = $attributes['name']['value'];
            $value = $attributes['value']['value'];
            if($name=='ga:profileId'){
                $profileId = $value;
            }
            echo "$name : $value\n";
        }       
        /** Get Analytics Account Information * */
        
        
        /** Get Analytics Data */         
        $dimensions = array(
            Zend_Gdata_Analytics_DataQuery::DIMENSION_MEDIUM,
            Zend_Gdata_Analytics_DataQuery::DIMENSION_SOURCE,
            Zend_Gdata_Analytics_DataQuery::DIMENSION_BROWSER_VERSION,
            Zend_Gdata_Analytics_DataQuery::DIMENSION_MONTH,
        );

        $query = $service->newDataQuery()->setProfileId($profileId)
                ->addMetric(Zend_Gdata_Analytics_DataQuery::METRIC_BOUNCES)
                ->addMetric(Zend_Gdata_Analytics_DataQuery::METRIC_VISITS)
                ->addFilter("ga:browser==Firefox")
                ->setStartDate('2013-05-01')
                ->setEndDate('2014-05-31')
                ->addSort(Zend_Gdata_Analytics_DataQuery::METRIC_VISITS, true)
                ->addSort(Zend_Gdata_Analytics_DataQuery::METRIC_BOUNCES, false)
                ->setMaxResults(1000);
        echo "\nVisits : Bounce \n\n";
        foreach ($dimensions as $dim) {
            $query->addDimension($dim);
        }
        try{
                   $result = $service->getDataFeed($query); 
        }catch(Exception $e){
            echo $e->getMessage();die;
            
        }

        foreach ($result as $row) {
            echo $row->getMetric('ga:visits') . "\t";
            echo $row->getValue('ga:bounces') . "\n";
        }
        /** Get Analytics Data */


As an above example, you can extract all information from the Google Analytics API and stored in array or Object then can download into csv OR Excel format.




Wednesday 14 May 2014

Zend_Filter_Input - Zend_Filter - Zend Framework

When user submit the data through Form, Developer need to filter the submitted data. because we can not trust on end user, he can be hacker. User can be add invalid data that cause, crash your page OR website. So Never trust on user and  always filter form data before saving in your database OR showing in website.

In Zend Framework, we can filter data differently with different field in single function. There is not need to use two different functions, one for filter and second for validator. There is zend_filter_input which can perform these two task. Lets take an example.

For Example 
In Age, We need to trim all Alphabets, only number is accepted
In Name, W need to trim all except alphabets
In DOB, We need to trim all except number and hyphen(-)

In Description, We need to removed all scripts tags because It can be XSS Attack.

We can add different filters on different fields. For Example in below code:
We add strip_tags and trim for Name and Address
We allow Alphanumeric and space for Address



Use following code to filter Form-Data in Zend Framework
  $formData = array(
            'name' => ' arun ..7809890809843 !@#$%%%',
            'address' => 'filter data *)(*)('
        );        
        $filters = array(
            '*' => array('StripTags', 'StringTrim'),
            'address' => array(array('Alnum', array('allowwhitespace' => true))),
        );

        $data = new Zend_Filter_Input($filters, null, $formData);
        $filterData = $data->getEscaped();        
        print_r($filterData);

5 Best Related Posts are Following:1. Web service - current time zone for a city- Free API
2. Zend Gdata Youtube API - Search Video - View Video Detail
3. Download the video from Amazon Simple Storage Service S3
4. How to set Cron in Zend Framework
5. Zend Cache Tutorial - Zend Framework 1.12

PHP Upload File In Amazon S3 Bucket - Code Snippets

PHP Upload File In Amazon S3 Bucket - Code Snippets

Get List of buckets in Amazon S3 bucket and upload a file in Amazon S3 bucket with Zend Framework.

Uploading files in zend framework is very simple because zend framework provides the API which is very simple to use.

Please use following code to upload photos in zend framework.
$my_aws_key = 'AWS_KEY';
$my_aws_secret_key = 'AWS_SECRET_KEY';
$s3 = new Zend_Service_Amazon_S3($my_aws_key, $my_aws_secret_key);

/** Get List of buckets * */
$list = $s3->getBuckets();
foreach ($list as $bucket) {
    echo "Bucket: $bucket\n";
}
/** Get List of buckets * */


/** get Bucket Files **/
$files = $s3->getObjectsByBucket("BUCKET_NAME");
foreach ($files as $file) {
    echo "File: $file\n";
}
/** get Bucket Files **/


$imageName = 'http://static.zend.com/img/yellowpages/ZFCE-logo-XS.jpg';
try {
    $s3->putFile($imageName, "BUCKET_NAME/ZFCE-logo-XS.jpg", array(
        Zend_Service_Amazon_S3::S3_ACL_HEADER => Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ,
        'x-amz-storage-class' => 'REDUCED_REDUNDANCY'
            )
    );
die('uploaded successfully');
} catch (Exception $e) {
    pr($e->getMessage());
    die;
}

Tuesday 18 March 2014

Difference Between Zend framework 2 VS Zend framework 1

Zend framework is framework created by zend company who is owner of PHP. It means it is more reliable as compare to other framework and CMS. That's why most of people are using Zend for their project. 


It is lots of qualities and are below:

  1. Its created by zend.com - Owner of PHP.
  2. Most of the third party API like GData, PDF, AUth, ACL etc are available.
  3. They provide support .
  4. Time by time, Up-dation are available so that you get always best in the industry.
  5. Excellent tutorial is available not for current version but also for previous version.

Now, Zend have provided Version2 because they always provide better to the php developer. Zend2 has its own qualities. Now we have more reason to select zend in our project.


Before start working zend2 we should compare with zend1 and get to know pros/cons of zend2.


So, Here are few compare of Zend framework 2 VS Zend framework 1.


Architecture:
ZF1 is based on MVC (Model View Controller)
ZF2 is based on MOVE (Model Operations Views Events)

Conventions:
Class name in ZF1 was Zend_Db_Table for class in Zend/Db/Table.php 
Class name in ZF2 is Zend\Db\Adapter for class in Zend/Db/Table.php 

Community:
ZF1 was backed by Zend Technologies (and few other, unnamed).
ZF2 was backed by Zend Technologies, Google and Microsoft.

Size of installation:
30Mb for ZF1
2.5 for ZF2 (zipped)

Performance:
PHP: ZF2 is 4 times slower than ZF1
Because ZF2 call more functions in background as compare to ZF1.
SQL: ZF2 is little  Faster than ZF1 

Compare Performance

  1. http://www.developerknowhow.com/zf1-vs-zf2/
  2. http://www.enrise.com/2012/02/zend-framework-2-performance/

For More detail, Please visit zend.com

Wednesday 5 March 2014

Zend Database Query - Zend Profiler Example - Code Snippets

Zend Profiler: It is used to display the queries executed by zend indirectly with MySql. It will show all the queries like insert, update, delete etc.

Zend Profiler is very important just because it show the queries but It can help you to improve the performance of your website.

See How you can use the Zend Profiler.
  1. With zend profiler you will get to know what type of queries are running in your application and which is making slow your website.
  2. Zend Profiler also also how much time each query is taking to execute.
  3. you can get to know, what are un-necessary queries are running
  4. What queries are running multiple times
  5. For future you can store these queries for further use.


 See below Example, How to use zend Profiler

//create class
class Application_Model_Test extends Zend_Db_Table_Abstract {
    protected $_name = 'tests';
    protected $_primary = 'id';

    //create function
    function insertData($data) {
        /** enable the zend profiler **/
        $this->getAdapter()->getProfiler()->setEnabled(true);
        $profiler = $this->getAdapter()->getProfiler();
        /** enable the zend profiler **/

        //save data
        $this->insert($data);

        /** to list the mysql queries * */
        foreach ($profiler->getQueryProfiles() as $query) {
            $sqlQuery = $query->getQuery();
            $params = $query->getQueryParams();
            echo $sqlQuery = str_replace(array('?'), $params, $sqlQuery);
            echo '';            
        }
        
        /** to list the mysql queries * */
    }
}




5 Best Related Posts are Following:1. Web service - current time zone for a city- Free API
2. Zend Gdata Youtube API - Search Video - View Video Detail
3. Download the video from Amazon Simple Storage Service S3
4. How to set Cron in Zend Framework
5. Zend Cache Tutorial - Zend Framework 1.12 

Saturday 14 December 2013

CURL Example

CURL
CURL is a library and command-line tool for transferring data using various protocols like HTTP, FTP, SCP, PUT, POST, POP3 & SMTP etc. It also used for scrapping the data from websites. We can scrap get the text as well as images with use of CURL.


It have two products libcurl and cURL.

cURL: Its command line tool for transferring information.
Libcurl: It is a free client-side URL transfer library.


CURL COMMAND-LINE EXAMPLE

Curl Example with "GET" Method (By Default GET)
curl http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "PUT" Method
curl --request PUT http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "DELETE" Method
curl --request DELETE http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method and pass data (Data: username, password & logintype)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html
--data 'username=user&password=****&logintype=normal' 

Curl Example with "POST" Method and pass data(data in text file)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt

Curl Example with "POST" Method, pass data and pass header
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' 

Curl Example with "POST" Method, pass data and pass header (Get Header in response) --include
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' --include

CURL LIBCURL EXAMPLE

Mostly to get data from an REST API, we use following method in php
echo file_get_contents('http://www.web-technology-experts-notes.in/p/sitemap.html');
But if, "allow_url_fopen" is disable in php.ini file due to security reason then above will not work. You need to use below code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.co.in");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;die;


CURL Example with Post Method with parameter
$url = "http://localhost/test/index2";
$post_data = array(
            "foo" => "bar",
            "foo1" => "testdata"
);
try {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $output = curl_exec($ch);
    curl_close($ch);
} catch (Exception $e) {
    echo $e->getMessage();die;
}

File Upload with CURL in PHP
 $file_name_with_full_path = realpath('uploadFile.zip');        
        $url = "http://localhost/test/index2";
        $post_data = array(
            "foo" => "bar",
            "upload" => "@".$file_name_with_full_path
        );
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
        } catch (Exception $e) {
            echo $e->getMessage();
            die;
        }
        
Transfer the File through FTP
curl_setopt_array($ch, array(
    CURLOPT_URL => 'ftp://ftp.example.com/test.txt',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => 'username:password'
));
 
$output = curl_exec($ch);

Set Header and Json data in Curl
$url='http://www.web-technology-experts-notes.in/';
$jsonData='{"name":"arun","email":"arun@gmail.com"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'X-API-Token: ' . X_API_TOKEN,
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));

curl_setopt($ch, CURLOPT_INTERFACE, "xxx.xxx.x.xx");
echo curl_exec($ch);
curl_close($ch);
Following are some Options which can be set be set in "curl_setopt" function


CURLOPT_REFERER - Set the Http Refer

CURLOPT_USERAGENT - Set the UserAgent

CURLOPT_HEADER - Include the header in response or not

CURLOPT_RETURNTRANSFER - Print the output or not

CURLOPT_URL - Set the URL (Uniform Resource Locator)

CURLOPT_POST - set 0 or 1 for post method

CURLOPT_POSTFIELDS - set the data which you want to post

CURLOPT_FOLLOWLOCATION - if set true, cURL will follow redirects

CURLOPT_CONNECTTIMEOUT -Total seconds to spend attempting to connect

CURLOPT_TIMEOUT - Total Seconds to allow cURL to execute






Zend Curl Example

$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'ssltransport' => 'tls',
    'strict' => false,
    'persistent' => true,
);
$url = 'http://www.example.com';
$client = new Zend_Http_Client($url, $config);
$postArray = array('name'=>'Georage','age'=>33);
$client->setParameterPost($postArray);
/** set Headers **/
$client->setHeaders(array(
    'Host: www.example.com',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
    'Accept: text/javascript, application/javascript, */*',
    'Accept-Language: en-gb,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With: XMLHttpRequest',
    'Referer: http://example.com'
));

/** set cookie **/
$client->setCookie('__utma', '174057141.1507422797.1392357517.1392698281.1392702703.3');
$client->setCookie('__utmz', '174057141.1392357517.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)');
$client->setCookie('__atuvc', '58');
$client->setCookie('PHPSESSID', '0a12ket5d8d7otlo6uh66p658a5');
$response = $client->request('POST');

$data= $response->getBody();
echo $data; 

Zend CURL Ignore SSL_VERIFYPEER
$url='www.example.com';
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'curloptions' => array(
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_SSL_VERIFYPEER => FALSE
    ),
);
 $client = new Zend_Http_Client($url, $config);
 $response = $client->request('GET');

Set CURL'S Timeout in Milli-seconds
 $ch = curl_init();
          //set the curl for crawl
          curl_setopt($ch, CURLOPT_URL, "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html");
          //include the header in the output
          curl_setopt($ch, CURLOPT_HEADER, 0);
          //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
          //The maximum number of milliseconds to allow cURL functions to execute.
          curl_setopt($ch, CURLOPT_TIMEOUT_MS, 4000); //timeout in seconds
          $output = curl_exec($ch);
          curl_close($ch); 

Set Zend CURL'S Timeout in Milli-seconds
$config = array(
            'adapter' => 'Zend_Http_Client_Adapter_Curl',
            'curloptions' => array(
                CURLOPT_FOLLOWLOCATION => FALSE,
                CURLOPT_HEADER => false,
                //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                CURLOPT_TIMEOUT_MS => 3000,
                //The maximum number of milliseconds to allow cURL functions to execute.
                CURLOPT_CONNECTTIMEOUT_MS => 3000
            )
        );
        $url = "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html";
        $client = new Zend_Http_Client($url, $config);
        $response = $client->request('GET');
        $output = $response->getBody();



Question: How to Set the username/password in CURL?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked"  "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to pass binary data(file) in CURL ?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to store linux command output in file?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" > output1.txt