Thursday, 29 December 2011

How to Disable Facebook News Ticker in Google Chrome


Social Networking giant Facebook has unveiled its new design with improved news feed. Facebook has also added a Twitter- like real-time news stream feature called ‘Ticker’ that shows you recent updates from those who are currently active on Facebook.
disable facebook real time feed news ticker
Some Facebook users are finding this ticker annoying. Moreover, it’s one of the controversial features of Facebook, that allows you to spy on others activities. I’ve been searching for solution to disable it, some people suggested reverting Facebook to UK English. But I’ve found another way; some geek has already developed a chrome extension to disable it. This extension seems great, now no distracting scrolling sidebar.
If you are a Google Chrome user, then use this extension to disable the Facebook new Ticker. Note that, this extension only works on Google Chrome.

[+/-] Read More...

Monday, 26 December 2011

How to handling larger database



Database server: Buy a server that can handle larger data's

Database engine: We can use either MyISAM or INNODB.

Stick to your basics right:
1)     Create table with proper indexing & primary key

2)     Don't use COUNT * on Innodb tables for every search, do it a few times and/or summary tables, or if you need it for the total # of rows, use SQL_CALC_FOUND_ROWS and SELECT FOUND_ROWS()

3)     Avoid using IN(...) when selecting on indexed fields, It will kill the performance of SELECT query.

4)     Use index to filter rows while searching

5)     Don’t use * in select when you’re not going to retrieve 60% of the columns. Make it specific like (userid, username, doj, lastlogin etc)

6)     Don't Index Everything

7)     A NULL data type can take more room to store than NOT NULL

8)     Use mysql_pconnect instead of mysql_connect in PHP

9)     Don’t use parenthesis in the select query instead use the table name as prefix for the column name.

10)  In the pagination don’t use offset, Just use Limit N. It makes pagination faster.
E.g.: With offset Select * from pages limit 10,20
Without offset Select * from pages where id > 10 limit 20

11)  Use INET_ATON and INET_NTOA for IP addresses

Optimization Tips:
1)     Use OPTIMIZE for each table
a.      E.g. OPTIMIZE Table tablename
                                                              i.      This will work only in MYISAM Engine.

                                                            ii.      While optimizing the entire table will be locked, so it should be done only when the site is offline & maintenance period

2)     To test the server speed, Just execute the following query in mysql
a.      SELECT BENCHMARK(1000000,10+10);

b.      The above command executes the expression 10 + 10 one million times. This will return 0 as result, but the execution time should be noted.
This command as to run different time of the day to check how the server handles the request.

3)     Create index for the table, we should make proper indexing to the fields which we’re going to search for the results.

4)     Before making a select query check it with Explain function & check whether the query is optimized to its best. This will be very useful when we use for complex queries.

5)     Use stored procedures to avoid bandwidth wastage

6)     Partition your database/table

7)     Delete data that you don’t need. Tables will grow, so monitor table sizes regularly.

Secure the Data’s:
While inserting or fetching data’s from the website, we need to be careful. We should follow the steps mentioned below
1)     Use mysql_real_escape_string() for the datas that has user interaction like Inserting fields & query strings

2)     Use POST method as much as possible

3)     Filter each inputs to make it secure. Use strip_tags().

4)     When you're getting the values from query string, use (int) function for getting integer values & if you want to get a string or characters use substring to get the values to a certain limit (For example: An hacker can pass ascii code to the query string & can access the database. So, we can limit upto 10 characters in the query string. If we do so, sql injection will be prevented).

5)     If you're using AJAX, pass the values by post method.

6)     Don't allow php files & other executable files in the file upload option. If you do so, the hackers can write their script in php file & upload it to your server & can access any data’s that they want.

7)     In production path don't print the mysql error code or sql query. If any error displayed then the hackers can find out the table structure for the website & can use it accordingly.

[+/-] Read More...

Frequently asked php and mysql top 10 interview question

Q:1
How can we submit a form without a submit button? 

A:1
The main idea behind this is to use Java script submit() function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit() method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites).

Q:2
In how many ways we can retrieve the data in the result set of MySQL using PHP? 

A:2
You can do it by 4 Ways
1. mysql_fetch_row.

2. mysql_fetch_array

3. mysql_fetch_object

4. mysql_fetch_assoc

Q:3
What is the difference between mysql_fetch_object and mysql_fetch_array? 

A:3
mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Q:4
What is the difference between $message and $$message? 
A:4
It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.

Q:5
How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP? 


A:5
preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);

echo $found[1];

Q:6
How can we create a database using PHP and MySQL? 

A:6
We can create MySQL database with the use of

mysql_create_db(“Database Name”)

Q:7
What are the differences between require and include, include_once and require_once? 

A:7
The include() statement includes and evaluates the specified file.The documentation below also applies to require(). The two constructs are identical in every way except how they handlefailure.include() produces a Warning while require() results in a Fatal Error. In other words, use require()if you want a missingfile to halt processing of the page.

include() does not behave this way, the script will continue regardless.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only differencebeing that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once() should be used in cases where the same file might be included and evaluated more than once during a particularexecution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once()
 should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
Q:8
Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:8
Yes we can use include() more than one time in any page though it is not a very good practice.

Q:9
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ? 


A:9
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM

MyISAM is the default storage engine as of MySQL 3.23 and as a result if we do not specify the table name explicitly it will be assigned to the default engine.

Q:10
How can we encrypt the username and password using PHP? 
A:10
The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT()   DES_DECRYPT()

ENCRYPT()       Not available

MD5()           Not available

OLD_PASSWORD()  Not available

PASSWORD()      Not available

SHA() or SHA1() Not available

Not available   UNCOMPRESSED_LENGTH()   

[+/-] Read More...

Sunday, 25 December 2011

What is the use of ini_set() in php

ini_set — Sets the value of a configuration option


syntax:
            string ini_set ( string $varname , string $newvalue )


here is the example:


<?phpecho ini_get('display_errors');

if (!
ini_get('display_errors')) {
    
ini_set('display_errors'1);
}

echo 
ini_get('display_errors');?>

[+/-] Read More...

Saturday, 24 December 2011

How to retrieve contacts from gmail using php classes

After long search i found one solution to grab the gmail contacts using php classes.
This class can be used to grab the contact lists of an Gmail user.It can authenticate in Google with the user name and password of a given account. Then it can retrieve the contact lists from the Gmail user address book.The retrieved contact lists are parsed and returned as arrays.


GrabGmail .class



<?php   class GrabGmail
  
{
     
//To use it in PHP4, please replace each "private" by "var"
     
var $contactListArray = array();
     var 
$contactListTable;
     var 
$requireCaBundle false;
     var 
$caBundleFile;
     var 
$cookiePath;
     var 
$proxyUrl='';
     var 
$userId     ='';
     var 
$password   ='';
     var 
$url        "https://www.google.com/accounts/ServiceLoginAuth";
     var 
$refererUrl "https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/?ui=html&zy=f&ltmpl=yj_blanco&ltmplcache=2&hl=en";

     
/**
     * Sets login information of Gmail account
     * @param user id and password
     * @return none
     */
     
function setLoginInfo($userId$password)
     {

        
$this->userId   $userId;
        
$this->password $password;

     }
//EO Method

     /**
     * Sets cookie save path(where cookie will be saved)
     * @param cookie path
     * @return none
     */
     
function setCookiePath($cookiePath)
     {
        
$this->cookiePath $cookiePath;
     }

     
/**
     * Sets proxy information if any
     * @param proxy URL
     * @return none
     */
     
function setProxy($proxyUrl)
     {
        
$this->proxyUrl $proxyUrl;
     }

     
/**
     * Sets Certificate Bundle File (this is necessary in accessing Gmail from localhost)
     * @param user id and password
     * @return none
     */
     
function setCaBundleFile($fileName)
     {
        
$this->requireCaBundle true;
        
$this->caBundleFile    $fileName//provide absolute path
     
}

     
/**
     * Checks whether proxy info is set
     * @param none
     * @return none
     */
     
function isProxy()
     {
        if(
$this->proxyUrl == '')
        {
           return 
false;
        }

        return 
true;

     }
//EO Method

     /**
     * Prepares contact list
     * @param none
     * @return none
     */
     
function prepareContactList()
     {

       if(
$this->userId == "" || $this->password=="")
       {
         die(
"Set Login Info");
       }
       else
       {
         
$this->postRequestToGmail();
       }

     }
//EO Method

     /**
     * Gets contact list in a table
     * @param none
     * @return Contact List Table
     */
     
function getResultTable()
     {
        if(!empty(
$this->contactListTable))
        {
           return 
$this->contactListTable;
        }
        else
        {
           return 
"List is Empty. Check your user id and password.";
        }
     }
//EO Method

     /**
     * Gets contact list in an array
     * @param none
     * @return Contact List Array
     */
     
function getResultArray()
     {
        if(
strlen($this->contactListTable)>33)
        {
           
$strValue $this->contactListTable;
           
$this->convertToArray($strValue);

           return 
$this->contactListArray;

        }
        else
        {
           return 
"List is Empty. Check your user id and password.";
        }
     }
//EO Method

     /**
     /** Modified On 05/25/07
     * Post request to Gmail, gets and parses contact list from Gmail
     * @param none
     * @return none
     */
     
function postRequestToGmail()
     {

        
$requestString  "service=mail&Email=".urlencode($this->userId)."&Passwd=".urlencode(str_replace(' ','+',$this->password))."&null=Sign%20in&continue=http%3A%2F%2Fmail.google.com%2Fmail%3F&rm=false&hl=en";
        
$user_agent     $_SERVER['HTTP_USER_AGENT'];
        
$cookie         1;
        
$cookieFileName md5($this->userId);

        
//setting cookie file. make sure the file has write permission
        
$cookieFileJar  = (isset($this->cookiePath))?($this->cookiePath"/" $cookieFileName) : ($_SERVER['DOCUMENT_ROOT'] . "/temp_dir/" $cookieFileName);

        
$cookieFile     $cookieFileJar;
        
$refererUrl     $this->refererUrl;

        
$c curl_init();
          
curl_setopt($cCURLOPT_URL$this->url);
          
curl_setopt($cCURLOPT_HEADER1);
          
curl_setopt($cCURLOPT_POST,   1);
          
//this referer tells Gmail that request is coming from Gmail
          
curl_setopt($cCURLOPT_REFERER$this->refererUrl);
          
curl_setopt($cCURLOPT_POSTFIELDS$requestString);

          
curl_setopt($cCURLOPT_RETURNTRANSFER1);

          
//Certificate information
        
if($this->requireCaBundle)
        {
          if(isset(
$this->caBundleFile))
          {
             
curl_setopt($cCURLOPT_CAINFO$this->caBundleFile);
          }
          else
          {
             die(
"Provide CA Bundle File");
          }
        }

        if(
$this->isProxy())
        {
           
curl_setopt($cCURLOPT_PROXY$this->proxyUrl);
          }

          
curl_setopt($cCURLOPT_SSL_VERIFYPEERFALSE);

          
curl_setopt($cCURLOPT_FOLLOWLOCATION1);
          
curl_setopt($cCURLOPT_USERAGENT$user_agent);

          
//writting cookie
          
curl_setopt($cCURLOPT_COOKIEJAR$cookieFileJar);
          
curl_setopt($cCURLOPT_COOKIE$cookie);

          
$res curl_exec($c);

          
curl_close($c);

        
$requestString ='http://mail.google.com/mail/h/ggggsdf/?v=cl&pnl=a&ui=html&zy=f';

        
//New curl session
        
$ch curl_init();

          
curl_setopt($chCURLOPT_URL$requestString);
          
curl_setopt($chCURLOPT_HEADER0);

          
curl_setopt($chCURLOPT_REFERER$refererUrl);
          
curl_setopt($chCURLOPT_RETURNTRANSFER1);

          
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);

          
//Certificate information
        
if($this->requireCaBundle)
        {
          if(isset(
$this->caBundleFile))
          {
             
curl_setopt($chCURLOPT_CAINFO$this->caBundleFile);
          }
          else
          {
             die(
"Provide CA Bundle File");
          }
        }

        if(
$this->isProxy())
        {
           
curl_setopt($chCURLOPT_PROXY$this->proxyUrl);
          }

          
curl_setopt($chCURLOPT_FOLLOWLOCATION1);
           
curl_setopt($chCURLOPT_USERAGENT$user_agent);

           
//reading cookie
           
curl_setopt($chCURLOPT_COOKIEFILE$cookieFile);

           
curl_setopt($chCURLOPT_COOKIE$cookie);

          
$gmailResponse curl_exec($ch);

          
curl_close($ch);

          
$parsedResponse  $this->parseResponse($gmailResponse);

          
$this->contactListTable $parsedResponse;

     }
//EO Method

     /** Modified On 05/25/07
     * Converts table data to array data
     * @param Table of Contact List
     * @return Contact List Array
     */
     
function convertToArray($strValue)
     {
        
$strVal str_replace("&nbsp;","",$strValue);
        
$output = array();
        
$strVal nl2br($strVal);
        
$strVal str_replace("<br />",'',$strVal);

        
## added on 01/23/07
        
$strVal preg_replace("/<span[^>]*?>.*?<\/span>/si",""$strVal);
        
$matches1 preg_match_all("/<b>([^<]+)<\/b>/si",$strVal,$outputPREG_PATTERN_ORDER);
        
$offset = array();
        
$matches2 preg_match_all("/<td[^>]*>([a-zA-Z0-9_\.]+@[a-zA-Z0-9_\.]+)?([^<]*)<\/td>/si",$strVal,$offsetPREG_PATTERN_ORDER);

        
//putting values into associative array
        
for($i=0;$i<sizeof($offset[2]); $i++)
        {
             
$email trim($offset[2][$i]);
             
$name  $output[1][$i];
           
$this->contactListArray[$email] =$name;
        }

     }
//EO Method

     /**
     * Parses Gmail Response String
     * @param Gmail Response
     * @return Parsed Response
     */
     
function parseResponse($str)
     {
        
$str nl2br($str);
        
$str str_replace("<br />","",$str);
        
$str preg_replace("/<script[^>]*?>.*?<\/script>/si",""$str);
        
$off = array();
        
$matches preg_match_all("/<table[^>]*?>.*?<\/table>/si"$str$off,PREG_PATTERN_ORDER);
        
$strVal $off[0][6];

        return 
$strVal;

     }
//EO Method

     /**
     * Debugs dump/data
     * @param $dump
     * @return none
     */
     
function dBug($dump)
     {

        echo 
"<PRE>";
        
print_r($dump);
        echo 
"</PRE>";

     }
//EO Method

  
}//EO Class
?>
How to use it:

just call this class by using object and pass gmail username and password as arguments


<?php   require_once("GrabGmail.class.php");
  
  
$login 'yourgmailid';//without "@gmail.com"
  
$password 'yourgmailpassword';
  
$cookiePath '/path/to/cookie/dir';  

  
$obj = new GrabGmail();
  
$obj->setLoginInfo($login$password);
  
$obj->setCookiePath($cookiePath);
  
$obj->setProxy("proxy.proxydomain.com:port");
  
$obj->prepareContactList();
  
$obj->dBug("========== All Contacts of <b>$login@gmail.com</b> ==============");
  
$obj->dBug('---- Contacts in Table ------');
  
$resultTable $obj->getResultTable();
  
$obj->dBug($resultTable);
  
$obj->dBug('---- Contacts in Array ------');
  
$resultArray $obj->getResultArray();
  
$obj->dBug($resultArray);     ?>

[+/-] Read More...