Thursday, 29 May 2014

Free Boost Web Application By 20% in Simple Steps

Simple Steps to Boost your appliction by 05 - 20%

  • echo is faster than print and use echo's for multiple parameters
  • Unset your large variables to free memory
  • use swtich case instead of if-else
  • Don't use @ because Error suppression with @ is very slow.
  • Turn on apache mod_deflate, mod_gzip which is available as an Apache module, compresses your data on the fly. It will boost your appliction and can reduce the data to transfer up to 80%
  • Incrementing/Decrementing a global variable is 2 times slower than a local variable
  • Incrementing/Decrementing an undefined local variable is 8 times slower than a initialized one.
  • use require instead of require_once
  • comment un-necessary code and remove the commented code
  • Avoid count(*) on entire tables, it can lock the entire table.
  • Use GROUP BY instead of DISTINCT when appropriate.
  • Use INSERT ON DUPLICATE KEY or INSERT IGNORE instead of UPDATE to avoid the SELECT prior to update.
  • Use Static Method, Speed improvement is by a factor of 4
  • Avoid necessary loops, because it may slow your application.

Friday, 23 May 2014

What is Streaming Servers, Streaming Protocol and Port Protocol

Streaming Servers: It is server which is more powerful in-terms of RAM, ROM, Processing & Disk spaces. These server kept the video/audio files and able to sent the video/audio in form of small packet(in right order) to the client machine bypass the webserver. 

Cleint Machhine Request the video/video to webserver => webserver sent the request to streaming server => Streaming server send the response in form of small packet to the clinet machine (By Passing the WebServer)

Why we need streaming server:

  • HTTP, FTP and TCP protocols  send the data in form of packets and reassembled later means first download full data in browser then play. In this case user have to wait  more time. where as in streaming server video playing and streaming simultaneouly. 
  • Streaming Server is more fast & better as compare to WebServer(Non-streaming Server).
  • Different Streaming Server use different type of protocol to enhance their speead and performace.


Web Server can re-send lost or damaged packets, and they allow randomly ordered packets to be reassembled later. This is convenient for downloading files and surfing the Web if Web traffic slows down or some of your packets disappear, you'll still get your file. But these protocols won't work as well for streaming media. With streaming media, data needs to arrive quickly and with all the pieces in the right order

PORT: PROTOCOL
20: File Transfer Protocol (FTP)
21: Secure File Transfer Protocol (SFTP)
22: Secure Shell (SSH)
25: Simple Mail Transfer Protocol (SMTP)
80: Hypertext Transfer Protocol (HTTP)
110: Post Office Protocol (POP3)
143: Internet Message Access Protocol (IMAP)
194: Internet Relay Chat (IRC)
443: Hypertext transfer Protocol Secure (HTTPS)
465: Simple Mail Transfer Protocol Secure (SMTPS)


Streaming Protocol
Apple HLS (HTTP Live Streaming)
RTMP, RTMPT, RTMPS, RTMPE, RTMPTE, Flash
Adobe HTTP Dynamic Streaming (HDS)
MS-WMSP (Windows Media HTTP Streaming Protocol), Windows Smooth Streaming, MMS, MMSH
RTSP, RTP, UDP
MPEG-DASH (HTTP)


Tuesday, 20 May 2014

Difference between WebService and API

Difference between WebService and API


S.No
Web Service
API
1
Interaction between two machines over a network. Interaction between two API.
2
Uses SOAP, REST, and XML-RPC as a means of communication. It may use any way to communication
3
Web Services involves calling of system. We can render form in one line, one by one element, element OR  decorator OR error separately.
4
Web service might not contain a complete set of specifications and sometimes might not be able to perform all the tasks that may be possible from a complete API. An API consists of a complete set of rules and specifications for a software program to follow in order to facilitate interaction.
5
All Web services are APIs All APIs are not Web services
6
A Web service always needs a network for its operation API doesn't need a network for its operation
7
WebServices are services available over internet. You can call these services and get so information in your application without know how it works. For example weather webservices gives you information about the city weather. API is a collection of class which provide you some functionality like Google api gives google-search.



Monday, 19 May 2014

PHP Check Mime Type of File - Return Information About A File

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. 
With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is  check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check  in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (http://php.net/manual/en/fileinfo.installation.php).


After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.
if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);    

    //file which you want to check the mime of the file
    $file = $_SERVER['DOCUMENT_ROOT'] . '/images/feedback.png';    //file which is going to get uploaded in web server
    try {
        $type = finfo_file($finfo,$file);        
        echo "File Type: ".$type;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo "'finfo_file' is Not installed";
}


When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.

Sunday, 18 May 2014

HR Interview Questions and Answers

  1. Tell me about yourself.
  2. Why should I hire you?
  3. What are your strengths and weaknesses?
  4. Why do you want to work at our company?
  5. What is the difference between confidence and over confidence?
  6. What is the difference between hard work and smart work?
  7. How do you feel about working nights and weekends?
  8. Can you work under pressure?
  9. Are you willing to relocate or travel?
  10. What are your goals?
  11. What motivates you to do good job?
  12. What makes you angry?
  13. Give me an example of your creativity.
  14. How long would you expect to work for us if hired?
  15. Are not you overqualified for this position?
  16. Describe your ideal company, location and job.
  17. What are your career options right now?
  18. Explain how would be an asset to this organization?
  19. What are your outside interests?
  20. Would you lie for the company?
  21. Who has inspired you in your life and why?
  22. What was the toughest decision you ever had to make?
  23. Have you considered starting your own business?
  24. How do you define success and how do you measure up to your own definition?
  25. If you won $10 million lottery, would you still work?
  26. Tell me something about our company.
  27. How much salary do you expect?
  28. Where do you see yourself five years from now?
  29. On a scale of one to ten, rate me as an interviewer.
  30. Do you have any questions for me?

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

Project Management Tips- Way to Successful project

Project Management Tips- Way to Successful project

Project Flow and Structure

Project Structure and flow must be clear to project manager, developer and client to avoid any problem in future. When basic flow will be clear to each of team then success rate of project will be increased. Use http://www.balsamiq.com/products/mockups to create the flow diagram and get approvel from client and make the aware of each member.

Keep communications: 
Keep the communication with client at-least weekly basis and  get the approvel of task done in whole week. Understanding must be good betweeen the team and client. If possible, each developer should be involved in communication.


Track of Project Status:
Track the current status of project by daily, weekly, to check that project in right direction.


Support to Developer:
Project manager must support and encourage his developer for each good work. So that team process in good way.




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;
}

Monday, 12 May 2014

Crontab Interview Questions and Answers


Crontab Interview Questions and Answers

A cron job is a Linux command for scheduling script on your server to complete repetitive tasks automatically. Scripts executed as a cron job are typically used to modify files, databases and manage caching.

Cron is controlled by "crontabs". There is the master file in /etc/crontab. Each user's cronjob is stored in /var/spool/cron/username directory.


Benefits of Cron
  • Cron already built, and works, very reliable
  • You more easily have control over when it runs. You control the minute, hour, day, month and weekday  etc.
  • You can run many cron with difference of 15 seconds
  • You can manage cronjob from admin panel
  • Need not run manually, Schedule once will execute manually.




Install crontab
crontab -a filename

Edit the crontab
$ crontab -e

Display crontab
crontab -l

Display the last edit the crontab file
crontab -v

Remove crontab
crontab -r

Following are the syntax for cron
minute(s) hour(s) day(s) month(s) weekday(s) command(s) "Argument1" "Argument2"
1 * 3 4 5 /path/to/command arg1 arg2

If you don't have parameter put star(*)


Description of Cron fields





Field       Description
minute(0-59) The exact minute that the command sequence executes
hour (0-23) The hour of the day that the command sequence executes
day(1-31)   The day of the month that the command sequence executes
month(1-12) The month of the year that the command sequence executes
weekday(0-6)         The day of the week that the command sequence executes (Sunday = 0, Monday = 1, Tuesday = 2, and so forth)
command(s) File Path    Absolute path CronFile
Argument               Argument (IF you want to pass an argument)

Unix Commands - All important commands which every developer should know

Unix Commands - All important commands which every developer should know

List all files and directory
$ ls

List all files and directory with their detail like permission, owner and created date
$ ls 
$ ls -l

List all files and directory with more option (when list is more than 1 page)
$ ls -l | more

Remove directory
$ rmdir dirname

Remove a file
$ rm filename

Remove a file without "confirmation"
$ rm -f filename

Remove a directory
$ rmdir filename

Copy source to destination
$ cp sourceFile destinationFile

Move a file from one location to another
$ mv source destination

Online manual (help) about command
$ man ls

Find a text in file and return that line
$ grep searchText fileName

Change the File/Directory Permission
$ chmod 644 fileOrDir

List the preprocessor
$ ps

Find text in List of processor
$ ps | grep STIME

Kill the process
$ kill 45555

Zip a file
$ gzip filename 

Unzip a file
$ ungzip filename.zip

List who is logged on your machine
$ who

List who is on the computer in the lab
$ finger

List of History you have done recently
$ history

Print the current Date
$ date

print the calendar for September 2000
$ cal 09 2013

See how much free disk space
$ df

Set the Alias for command
$ alias newc="ls -l";

Print system usage and top resource hogs
$ top

Logout from the putty/console
$ logout
$ exit

Progressively dump a file to the screen: ENTER = one line down SPACEBAR = page down  q=quit$ more filename

Show the firest few lines of a file
$ head filename
$ head -n  filename

Show the last few lines of a file
$ tail filename
$ tail -n  filename

Search the text and store the output in file
$ grep string filename > newfile
$ grep string filename >> existfile

Finds all the files named aaa.txt in the current directory or any subdirectory tree.
$ find . -name aaa.txt

Open a file in edit mode
$ vi filename

Open file in vi editor and go to line no 101 instant
$ vi +101 filename

Show the line number in front of each line in vi editor
:set number

Go to particular line number in vi editor
:14
:100
:5

Search text "searchme" in the vi editor
:/searchme
to search next press "n" and for previous "shift+n"

Come out from vi editor
"shift+:" and press "q" and then press "enter key"

Edit modes (These keys enter editing modes and type in the text of your document.)
i  Insert before current cursor position
I  Insert at beginning of current line
a  Insert (append) after current cursor position
A  Append to end of line
Open and put text in a new line below current line
O  Open and put text in a new line above current line
r  Replace 1 character
R  Replace mode
<ESC> Terminate insertion or overwrite mode


Deletion of text
x   Delete single character
dd  Delete current line and put in buffer
ndd Delete n lines (n is a number) and put them in buffer
J   Attaches the next line to the end of the current line (deletes carriage return).

Cut and paste
yy Yank current line into buffer
nyy Yank n lines into buffer
p  Put the contents of the buffer after the current line
P  Put the contents of the buffer before the current line

Cursor positioning  (symbol (^ )before a letter means that the <Ctrl> key should be held down while the letter key is pressed)
^d  Page down
^u  Page up
^f   move forward one screen
^b  move backward one screen
^g  Display current line number
:n   Position cursor at line n
:$  Position cursor at end of file


Give on which server you are on
$ uname
Linux

Give your hostname
$ uname -n;
$ hostname

Kill your task
$ kill 1202255

Command displays active processes
$ ps


Display today's CPU activity
$ sar

Change the File's timing (created, access and modification time);
$ touch file.txt
If file is not exist, If will create the file

set  the access and modify timestamp
$ touch -t 06151330 f1.c;

Get file stats
$ stat file.txt

Change the owner of file/folder
$ chown vivek demo.txt
Owner of demo.text is set to vivek

Change the owner & Group of file/folder
$ chown vivek:arun demo.txt
Owner of demo.text is set to vivek
Group of demo.text is set to arun

Change the group of file/folder
$chown :ftp demo.txt
Group of demo.text is set to ftp

Change the owner of folder
$chown root /folder
Owner of /folder set to root

Change the owner of folder and its subfolder
$chown -R root /folder
Owner of /folder and its sub folder, set to root

List of user
$ w
$ who

Number of files in folder
ls -l | wc -l

Number of files in folder including dot and hidden files
ls -lA | wc -l

List the files sort by date
ls -ltr

Execute URL in Lynx with credentials
lynx http://example.com/action.php -accept_all_cookies -auth=username:'password'

List the crontab in your application
$ crontab -l

Edit the crontab timings
$ crontab -e

Total files in Directory
ls -1 | wc -l

Get the Files size in MB (Mega bytes) in unix command
$ ls -lash

Show the list of files committed in revision 570 of SVN
svn log -r 570 -v

Show the list of previous 5 users who have commit the file in SVN
svn log -l 5

Show the previous 5 logs of AjaxController.php
svn log -l 5 AjaxController.php

Show the previous all logs of AjaxController.php
svn log AjaxController.php