Courtesy:-http://www.excellentwebworld.com/wordpress-interview-question-answer/

WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time.Now Most of users are started development on WordPress The main reason for its popularity is its admin very easy to use and manage.Its will work on apr. 60 million websites world wide.

So now all IT firm started hiring developer for WordPress but main thing what exact qualification we needed and exactly what knowledge we are looking for.So here is the some basic & Technical question answer that at-least developers knows.

In this blog find some technical Question & Answer of WordPress.

Que 1 How we will pass a variable by value in WordPress.
Ans. Its same like we will work in c,c++
$p = &$s

Que 2 Basic functions then we generally used in WordPress? Why?
Ans: If developer have good knowledge then he/she must know this function name at-least 3-5

1. is_page() :- Condition for check if page is displayed. Its return true or false.
2. wp_nav_menu() :- Enabling WordPress 3.0′s Navigation Menu Feature
3. wp_list_pages() :- Listing All Pages
4. get_excerpt() :- Displays the excerpt of the current post with read more link for display full post.
5. is_category() :- Condition for check if category is displayed. Its return true or false.
6. the_title():- Displays the title of the current post
7. the_content():- Displays the contents of the current post.
8. bloginfo(‘url’) :- Getting the Site’s URL
9. bloginfo(‘template_url’) :- Getting the URL to the Current Theme
10.the_time():- Display the time the post was published (uses PHP date formatting as a parameter):

Que 3 How many tables a default WordPress will have?
Ans If developer work with database then he/she must know how many table install with default wordpress.
A default wordpress will have 11 tables. They are-
1. wp_commentmeta
2. wp_comments
3. wp_links
4. wp_options
5. wp_postmeta
6. wp_posts
7. wp_terms
8. wp_term_relationships
9. wp_term_taxonomy
10.wp_usermeta
11.wp_users

Que 4 Is WordPress good for Google ranking and SEO?
Ans Yes, That is one of the major selling points of using WordPress is that it includes excellent built in search engine optimization (SEO).In Other CMS you have to install SEO extention they either free or Commercial.In WordPress you can also extend SEO feature by using some Nice FREE SEO plugins likes All in one SEO,Yoast These are popular plugins that are known to help your rank on search engines such as Google and Bing.

Que 5 How to hide the top admin bar at the frontend in WordPress.
Ans. Most of developer have no idea about this.
Add the below mentioned code in the theme(active) function.php

(or)
Add the below code in the active theme style.css stylesheet
#wpadminbar {
display: none; visibility: hidden;
}

Que 6 How to hide Directory Browsing in WordPress from server using .htaccess file?

By default when your web server does not find an index file (i.e. a file like index.php or index.html), it automatically displays an index page showing the contents of the directory.SO now if you want to hide this add below code in .htaccess file.

Que 7 What are the custom fields in wordpress? How to display it?
Ans We will add extra information to our post by using custom fields.Custom Fields are a form of meta-data that allows us to store arbitrary information with each WordPress post.
To display the Custom Fields for each post, use the the_meta() template tag.
To fetch meta values use the get_post_meta() function.
For example we use custom fields:-

Que 8 What is the use of loop in Worpdress Where we used it?
Ans. The Loop are php code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page.check below sample code.

Que 9 How to run database Query in WordPress?
Ans. The $wpdb->query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function. Check sample code below for SELECT query.

Que 10 How to Change Your Default WordPress Post Category & Post Type?
Ans. Most common issue and most of developer not know this and find hacking(custom coding solution).But it more easy then that.simply navigate to Settings > Writing > and then look for the pull down menu beside “Default Post Categoy.” for change default category selection.

Writing Setting
Below that you can find Default post format for changes post type from standard to image post type or a video post type,chat gallery,link and many more.

Que 11 How to Change the Length of the Default WordPress Excerpt.
Ans The default WordPress excerpt is 55 words long. By modified bit to your functions.php file you can change the length to as you required.Below is the code if we need 60 length.

Que 12 How to add option for open menu item in new tab?
Ans. This is very basic feature but sometime developer never use this so they have no idea and goto code and add manually that links.For add option in menu item for open link in new tab just navigate to “Screen Option” at top right corner in menu select check “link target”. See below screenshot.

Menus

Que 13 What is hooks and types of hooks in wordpress?Where it used?
Ans. Hooks are provided by WordPress to allow your plugin to ‘hook into’ WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two types of hooks used in WordPress are Actions and Filters.

1)Actions Run During a Typical Request.for example A developer may want to add code to the footer of a Theme. This could be accomplished by writing new function, then Hooking it to the wp_footer Action.
has_action()
add_action()
do_action()
do_action_ref_array()
did_action()
remove_action()
remove_all_actions()
2)Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.
has_filter()
add_filter()
apply_filters()
apply_filters_ref_array()
current_filter()
remove_filter()
remove_all_filters()
Que 14 What is child theme? Why we used it?
Ans A WordPress child theme is a WordPress theme that inherits its functionality from its parent WordPress theme.Child themes are often used when you want to customize or tweak an existing WordPress theme without losing the ability to upgrade that theme.
Advantage is child theme is Safe Updates,Easy to Extend,Fallback Safe

Que 15 What is the Basic Difference Between Posts vs. Pages.
Ans. Posts are timely vs. Pages are timeless.
Posts are social vs. Pages are NOT.
Posts can be categorized vs. Pages are hierarchical.
Posts are included in RSS feed vs. Pages are not.
Pages have custom template feature vs. Posts do not.


Courtesy:-http://hayageek.com/php-random-number/

In PHP Random Number Generator, I have explained how to Generate a random number with in a range / Generate a random string with given length.In PHP,  we can use rand() function to generate random number. using this function we can make random string also.

PHP rand() Syntax:

1
2
3
4
5
//Generates random number
int rand(void);
//Generate random number in range from $min , to $max (inclusive)
int rand($min,$max);

1).PHP Random Number

1
2
$rand_value =rand();
echo $rand_value."\n";

2).PHP Random Number in a Range(10..100)

1
2
$rand_value = rand(10,100); //generates a number from 10 to 100
echo $rand_value."\n";

3).PHP Generate Random String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function gen_random_string($length=16)
{
    $chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";//length:36
    $final_rand='';
    for($i=0;$i<$length; $i++)
    {
        $final_rand .= $chars[ rand(0,strlen($chars)-1)];
    }
    return $final_rand;
}
echo gen_random_string()."\n"; //generates a string
echo gen_random_string(8)."\n"; //generates a string with length 8

 

4).PHP Generate random number with given length

1
2
3
4
5
6
7
8
9
10
11
12
13
function gen_random($length=32)
{
    $final_rand='';
    for($i=0;$i< $length;$i++)
    {
        $final_rand .= rand(0,9);
    }
    return $final_rand;
}
echo gen_random(10)."\n";//random number with length 10
echo gen_random()."\n";//random number with length 32

Posted: March 8, 2014 in Php
Tags: , ,

Courtesy:-http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/

First, let me introduce what Contacts Data API and OAuth is.

OAuth

OAuth (Open Authorization) is an open standard for authorization. It allows users to share their private resources (e.g. photos, videos, contact lists) stored on one site with another site without having to hand out their credentials, typically username and password.

Google Contact Data APIs

The Contacts Data API allows client applications to view and update a user’s contacts. Contacts are stored in the user’s Google Account; most Google services have access to the contact list.

You can easily find many source codes for importing Gmail contacts by Googling. But most of them use outdated Google Contact Data API or OAuth. By using the latest APIs we can easily import the contacts with fewer lines of code and is much more efficient than the old version. OAuth is in its second generation today. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. OAuth 2.0 is not backward compatible with OAuth 1.0. Using the older APIs you couldn’t retrieve the contacts in local host. That is, it was difficult to modify or edit the code for the website as the code had to be uploaded again and again to the host. But with the help of new API you can try and edit the code in local host and it works efficiently.

In this tutorial we will be using OAuth 2.0 and Google Contacts Data API.

You can refer more about them at the links below.

http://code.google.com/apis/accounts/docs/OAuth2.html

http://code.google.com/apis/contacts/

As we had a little introduction about both the APIs, we will head to the Step by Step tutorial to import the contacts.

Step 1:

Create file ‘oauth.php’ in your web-host. For the example that I have shown, I made a folder ‘oauth’ in localhost and created the file ‘oauth.php’ in the folder.

Thus, in my case, the URL for the file is http://localhost/oauth/oauth.php

Please note your URL for the file, as you will need it in the later steps.

Now paste the code below into ‘oauth.php’ and save the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<html>
<head>
<meta name="robots" content="noindex" />
<title>Email address list - Import Gmail or Google contacts</title>
<style type="text/css">
	a:link {color:Chocolate;text-decoration: none;}
	a:hover {color:CornflowerBlue;}
	.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
	<div >
		<a href="http://25labs.com/" >
			<img style="padding-top: 10px;" src="http://25labs.com/wp-content/themes/TheStyle/images/logo.png"></img>
		</a>
	</div>
	<br/>
	<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/" >Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0 in PHP</a></div>
	<br/>
	<div style="padding-left: 50px;">
<?php
$client_id='Your Client ID goes here';
$client_secret='Your Client secret goes here';
$redirect_uri='Your Redirect URIs goes here';
$max_results = 25;

$auth_code = $_GET["code"];

function curl_file_get_contents($url)
{
 $curl = curl_init();
 $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

 curl_setopt($curl,CURLOPT_URL,$url);	//The URL to fetch. This can also be set when initializing a session with curl_init().
 curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);	//TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
 curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);	//The number of seconds to wait while trying to connect.	

 curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);	//The contents of the "User-Agent: " header to be used in a HTTP request.
 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);	//To follow any "Location: " header that the server sends as part of the HTTP header.
 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);	//To automatically set the Referer: field in requests where it follows a Location: redirect.
 curl_setopt($curl, CURLOPT_TIMEOUT, 10);	//The maximum number of seconds to allow cURL functions to execute.
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);	//To stop cURL from verifying the peer's certificate.

 $contents = curl_exec($curl);
 curl_close($curl);
 return $contents;
}

$fields=array(
    'code'=>  urlencode($auth_code),
    'client_id'=>  urlencode($client_id),
    'client_secret'=>  urlencode($client_secret),
    'redirect_uri'=>  urlencode($redirect_uri),
    'grant_type'=>  urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');

$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);
$result = curl_exec($curl);
curl_close($curl);

$response =  json_decode($result);
$accesstoken = $response->access_token;

$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$accesstoken;
$xmlresponse =  curl_file_get_contents($url);
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0)) //At times you get Authorization error from Google.
{
	echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
	exit();
}
echo "<h3>Email Addresses:</h3>";
$xml =  new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');

foreach ($result as $title) {
  echo $title->attributes()->address . "<br>";
}
?>
	</div>
</body></html>

Step 2:

To use the Google API, you need to register your product at Google. To start the Registration process, head to Google API Console.

If you haven’t created any projects yet, then you will be seeing a page as shown below. Click ‘Create Project…’ button.

Create Project

Create Project

If you have created a project earlier, then you will be taken to an existing project directly. Click on the drop down menu that has the current project’s name which is located at the top left of the webpage (In my case it is ‘API Project’) and click ‘Create…’ in ‘Other projects’ tab. Now you will be asked to enter the name of the project. Enter a name as you wish.

API Projects drop down

API Projects drop down

API drop down - Create

API drop down – Create

Step 3:

Click ‘API Access’ from the let menu.

API Access

API Access

Step 4:

Now click on ‘Create an OAuth 2.0 client ID…’ button on the page that just opened up.

Create OAuth client ID

Create OAuth client ID

Step 5:

Fill in a name for the project. When a user clicks to retrieve the contacts, this product name will be shown on the conformation page. So please provide a sensible name.

You can optional give a product logo. The maximum allowed size for the logo is 120 x 60 pixels. This logo will also be displayed on the user’s confirmation page.

Create Client ID

Create Client ID

After you fill in the details click ‘Next’ button.

Step 6:

Now you will be taken to Client ID settings page.

Choose ‘Web application’ radio button for the Application type.

In ‘Your site or hostname’ block, choose ‘http://’ or ‘https://’ as per your requirement.

Now, enter your domain for the web application. You can also provide ‘localhost’.

Create Client ID

Create Client ID

Now, click ‘more options’ which lies next to ‘Your site or hostname’.

Enter the url that we created in Step 1 as ‘Authorized Redirect URIs’.

You will automatically have your host address as ‘Authorized JavaScript Origins’. You can enter more origins if you wish.

Create OAuth client ID

Create OAuth client ID

Click ‘Create client ID’ button.

Step 7:

Now you have registered your product and you can view the API credentials for your web application.

Note down the Client ID, Client secret and Redirect URIs. You will need them in Step 8 and 9.

API Credentials

API Credentials

Step 8:

Open oauth.php that you created in Step 1.

Replace ‘Your Client ID goes here’, ‘Your Client secret goes here’ and ‘Your Redirect URIs goes here’ with the Client ID, Client secret and Redirect URIs that you created in Step 7, respectively.

You can optionally change the number next to ‘$max_results’. It specifies the maximum number of email addresses to be retrieved.

Step 9:

Create the button or link that the user needs to click to retrieve the contact list and set its href parameter to

'https://accounts.google.com/o/oauth2/auth?client_id=your_client_id_goes_here&redirect_uri=your_redirest_urls_goes_here&scope=https://www.google.com/m8/feeds/&response_type=code'

Replace ‘your_client_id_goes_here’ and ‘your_redirest_urls_goes_here’ with the Client ID and Redirect URIs that you created in Step 7, respectively.

Or you can optionally copy the code given below, replace ‘your_client_id_goes_here’ and ‘your_redirest_urls_goes_here’ as mentioned above, and save it as a new file, may be ‘index.php’.

Then save it to your host.

Please make sure that you place this file in a directory that satisfies ‘JavaScript origins’ that you specified in Step 6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<meta name="robots" content="noindex" />
<title>Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0</title>
<style type="text/css">
	a:link {color:Chocolate;text-decoration: none;}
	a:hover {color:CornflowerBlue;}
	.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
	<div class="logo" >
		<a href="http://25labs.com/" >
			<img style="padding-top: 10px;" src="http://25labs.com/wp-content/themes/TheStyle/images/logo.png"></img>
		</a>
	</div>
	<br/>
	<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/" >Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0 in PHP</a></div>
	<br/><br/>
	<div align="center" >
	<a  style="font-size:25px;font-weight:bold;" href="https://accounts.google.com/o/oauth2/auth?client_id=your_client_id_goes_here&redirect_uri=your_redirest_urls_goes_here&scope=https://www.google.com/m8/feeds/&response_type=code">Click here to Import Gmail Contacts</a>
	</div>
</body>
</html>

We have now successfully completed the web application to retrieve Gmail or Google contacts.

Testing the web application:

Now it’s the turn to test the application. Please follow the steps mentioned below.

Step 10:

Browse to the file that created in Step 9 using your favorite web browser. Click on the button or link that you created to retrieve the contacts.

There is a chance that you get an error similar to the one shown below, especially if you are trying it on localhost.

Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\oauth\oauth.php on line 24

If you are among the unlucky ones, please follow the procedure mentioned below to solve the issue.

Solution:

If you are on localhost open:

php/php.ini

php/browscap/php.ini (if existent)

php/php4/php.ini (if existent)

apache/bin/php.ini (if existent)

 

If you are on web host, open web host’s ‘php.ini’

 

Search for ‘extension=php_curl.dll’.

If not found add it to ‘Dynamic Extensions’ section.

If found, uncomment the statement.

Then restart Apache if on localhost.

Try Step 10 again.

Step 11:

You will be taken to a conformation page which will look similar to the one shown below.

Import Gmail Contacts

Import Gmail Contacts

Click ‘Allow Access’ button.

Step 12:

If everything went right, you will have a list of email addresses on screen.

Please comment below, if you have any queries or errors.

 


Courtesy:-http://www.a2zwebhelp.com/invite-friends-from-gmail

Google has introduced OAuth 2.0 and OAuth 1.0 has been officially deprecated as of April 20, 2012. So let us create a program to invite friends from Gmail using OAuth 2.0. Before you can use OAuth 2.0, you must register your application using the  Google APIs Console. First you need to create a project and follow the steps.

Create a New project:

Then Click on API Access to Create an OAuth 2.0 Client ID

Fill up the form to create your project

Setting your Client ID

Now you will get your Client ID, Client secret and Redirect URIs that we will use in our project. You can edit your Redirect URIs by clicking on Edit Setting in the right side. Once you have all info lets create our conig.php file.

config.php

In this file you have to enter Client ID, Client secret and Redirect URIs.

<?php
$clientid = 'Your Client here';
$clientsecret = 'Your Client Secret';
$redirecturi = 'http://your path/result.php'; 
$maxresults = 50; // Number of mailid you want to display.
?>


index.php

<?php include('config.php'); ?>

<a href="https://accounts.google.com/o/oauth2/auth?client_id=
<?php print $clientid;?>&redirect_uri=<?php print $redirecturi; ?>
&scope=https://www.google.com/m8/feeds/&response_type=code">
Invite Friends From Gmail</a>

 

result.php

<?php
include('config.php');
$authcode = $_GET["code"];
$fields=array(
'code'=> urlencode($authcode),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> urlencode('authorization_code') );

$fields_string = '';
foreach($fields as $key=>$value){ $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');

$ch = curl_init();//open connection
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);

$response = json_decode($result);
$accesstoken = $response->access_token;
if( $accesstoken!='')
$_SESSION['token']= $accesstoken;
$xmlresponse= file_get_contents('https://www.google.com/m8/feeds/contacts/
default/full?max-results='.$maxresults.'&oauth_token='. $_SESSION['token']);

$xml= new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
$count = 0;
foreach ($result as $title) {
$count++;
echo $count.". ".$title->attributes()->address . "<br><br>";
}
?>

Download all files from here

Download Project Files


Courtesy:-http://codeitall.wordpress.com/2012/01/21/yahoo-oauth-to-import-contacts/

This is similar to Gmail OAuth.

First get the API KEY from Yahoo.

Then set the application’s access on the proceding page. Like set Messanger Access Contact, then access the data for Contacts.

Get the App ID, Consumer Key, and Consumer Secret.

Then start coding the below lines.

config.php

<?php $app_id = '[Enter the Application ID]'; $consumer_key = '[Enter the Consumer Key]'; $consumer_secret= '[Enter the Consumer Secret]'; $connected_path = 'Connected.php'; $re_url = "[Enter the path to Connected.php]/Connected.php"; ?>

ReadyGetConnection.php

<?php include_once 'config.php'; ?> <a href="<?=$connected_path?>">Connect me with Yahoo</a>

Connected.php

<? include_once 'config.php'; require_once ('Yahoo.inc'); $session = YahooSession::requireSession($consumer_key,$consumer_secret,$app_id); if (is_object($session)) { $user = $session->getSessionedUser(); $profile = $user->getProfile(); $name = $profile->nickname; // Getting user name $guid = $profile->guid; // Getting Yahoo ID $contacts=$user->getContacts()->contacts; echo "Hi! ".$name."<br />"; for ($i=0,$k=0;$i<count($contacts->contact);$i++) { for($j=0;$j<count($contacts->contact[$i]->fields);$j++) { $url_data = $contacts->contact[$i]->fields[$j]->uri; $url_pie=explode("/user/", $url_data); $url_end=substr($url_pie[1], stripos($url_pie[1], "/")+1); $data=explode("/", $url_end); if ($data[2]==="email") { $email_fr[$k]=$user->getDatafrom($url_end)->email->value; $k++; } } } echo "You have ".$k." contacts.<br />"; for($i=0;$i<$k;$i++) echo ($i+1).": ".$email_fr[$i]."<br />"; } else { header("Location :".$re_url); }

Yahoo.inc can be downloaded here.


Courtesy:-http://www.idiotminds.com/get-the-contacts-list-from-yahoo-account/

 

Now a days,website s are widely using the open invite system .Here,We used Yahoo Oauth for getting the contacts list from yahoo account using Yahoo PHP SDK.Contacts are relationships that exist in Yahoo! address book, such as those entered from across the Yahoo! Network like Yahoo! Mail and Yahoo! Messenger. The API provides read and write access.
Before starting with the Yahoo PHP SDK, you will need to register a web application and you will get web-based application ID,OAuth consumer key and secret. These keys will provide you with general access to the Yahoo! Social Platform, and allow your users to authorize your application to access protected resources and information.

 

Live DemoLive Demo

Download Script

For Creating the Yahoo App,Please Click Here.

In Yahoo My projects page,Click on the New Project Button.It will appears a popup.In that popup,select the Standard option.

Yahoo Application Type

In that Popup click on Continue button after selection of the Yahoo Application type,you will get the Application form.

Yahoo Application Form

After filling the all fields,Click on the Get API Key.You will get application ID,OAuth consumer key and secret.

Yahoo Authentication Information

After that you need to set the permissions for this app.In the Permissions,You need to select the Read Public option under Social Directory (Profiles) of the Social Directory and after you need to click on Save and Change Consumer Key.

Yahoo Contacts

Here is the index.php file.In that file you need to define the OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_DOMAIN, OAUTH_APP_ID

  1. <?php
  2. // Include the YOS library.
  3. require dirname(__FILE__).’/lib/Yahoo.inc’;
  4. //for converting xml to array
  5. function XmltoArray($xml) {
  6.         $array = json_decode(json_encode($xml), TRUE);
  7.         foreach ( array_slice($array, 0) as $key => $value ) {
  8.             if ( empty($value) ) $array[$key] = NULL;
  9.             elseif ( is_array($value) ) $array[$key] = XmltoArray($value);
  10.         }
  11.         return $array;
  12.     }
  13. YahooLogger::setDebug(true);
  14. YahooLogger::setDebugDestination(‘LOG’);
  15. // use memcache to store oauth credentials via php native sessions
  16. //ini_set(‘session.save_handler’, ‘files’);
  17. //session_save_path(‘/tmp/’);
  18. session_start();
  19. // Make sure you obtain application keys before continuing by visiting:
  20. // https://developer.yahoo.com/dashboard/createKey.html
  21. define(‘OAUTH_CONSUMER_KEY’, ‘Your App Consumer Key’);
  22. define(‘OAUTH_CONSUMER_SECRET’, ‘Your App Consumer Secret’);
  23. define(‘OAUTH_DOMAIN’, ‘Your Domain’);
  24. define(‘OAUTH_APP_ID’, ‘Your App Id’);
  25. if(array_key_exists(“logout”, $_GET)) {
  26.   // if a session exists and the logout flag is detected
  27.   // clear the session tokens and reload the page.
  28.   YahooSession::clearSession();
  29.   header(“Location: index.php”);
  30. }
  31. // check for the existance of a session.
  32. // this will determine if we need to show a pop-up and fetch the auth url,
  33. // or fetch the user’s social data.
  34. $hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
  35. if($hasSession == FALSE) {
  36.   // create the callback url,
  37.   $callback = YahooUtil::current_url().”?in_popup”;
  38. $sessionStore = new NativeSessionStore();
  39.   // pass the credentials to get an auth url.
  40.   // this URL will be used for the pop-up.
  41.   $auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback, $sessionStore);
  42. }
  43. else {
  44.   // pass the credentials to initiate a session
  45.   $session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
  46.   // if the in_popup flag is detected,
  47.   // the pop-up has loaded the callback_url and we can close this window.
  48.   if(array_key_exists(“in_popup”, $_GET)) {
  49.     close_popup();
  50.     exit;
  51.   }
  52.   // if a session is initialized, fetch the user’s profile information
  53.   if($session) {
  54.     // Get the currently sessioned user.
  55.     $user = $session->getSessionedUser();
  56.     // Load the profile for the current user.
  57.     $profile = $user->getProfile();
  58.     $profile_contacts=XmltoArray($user->getContactSync());
  59.    $contacts=array();
  60.    foreach($profile_contacts['contactsync']['contacts'] as $key=>$profileContact){
  61.        foreach($profileContact['fields'] as $contact){
  62.           $contacts[$key][$contact['type']]=$contact['value'];
  63.        }
  64.    }
  65.   }
  66. }
  67. /**
  68.  * Helper method to close the pop-up window via javascript.
  69.  */
  70. function close_popup() {
  71. ?>
  72. <script type=”text/javascript”>
  73.   window.close();
  74. </script>
  75. <?php
  76. }
  77. ?>
  78. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”>
  79. <html>
  80.   <head>
  81.     <title>Get the contact list from Yahoo-Idiot Minds</title>
  82. <style type=”text/css”>
  83. body{
  84. background-color: #F2F2F2;
  85. }
  86. .yh_frnds{
  87.     list-style:none;
  88. }
  89. .yh_frnds li{
  90.     padding:10px;
  91.     float:left;
  92.     width:30%;
  93. }
  94. .frnd_list{
  95.     margin-top:-25px;
  96.     margin-left:40px;
  97. }
  98. .fb_frnds a{
  99.         text-decoration:none;
  100.          background: #333;
  101.          filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#333′, endColorstr=’#D95858′); /* for IE */
  102. background: -webkit-gradient(linear, left top, left bottom, from(#333), to(#D95858)); /* for webkit browsers */
  103. background: -moz-linear-gradient(top,  #333,  #D95858)/* for firefox 3.6+ */ ;
  104.     color: #FFFFFF;
  105.         float: right;
  106.         font: bold 13px arial;
  107.         margin-right:110px ;
  108. }
  109. </style>
  110.     <!– Combo-handled YUI JS files: –>
  111.     <script type=”text/javascript” src=”yahoo-dom-event.js”></script>
  112.     <script type=”text/javascript” src=”popupmanager.js”></script>
  113.   </head>
  114.   <body>
  115.     <?php
  116.       if($hasSession == FALSE) {
  117.         // if a session does not exist, output the
  118.         // login / share button linked to the auth_url.
  119.         ?>
  120.        <a href=”<?php echo $auth_url; ?>” id=”yloginLink”><img src=”yahoo-oauth-connect.png” style=”width:150px;margin-left: 350px;” title=”Get the contact list from Yahoo-Idiot Minds” alt=”Get the contact list from Yahoo-Idiot Minds” /></a>
  121.     <?php  }
  122.       else if($hasSession && $profile) {
  123.         // if a session does exist and the profile data was
  124.         // fetched without error, print out a simple usercard.
  125.        ?>
  126.       <img src=”<?php echo $profile->image->imageUrl; ?>” style=”width:10%;” />
  127.       <h2>Hi <a href=”<?php echo $profile->profileUrl; ?>” target=”_blank”><?php echo $profile->nickname; ?></a>
  128.       </h2>
  129. <?php
  130.         if($profile->status->message != “”) {
  131.           $statusDate = date(‘F j, y, g:i a’, strtotime($profile->status->lastStatusModified));
  132.           echo sprintf(“<p><strong>“</strong>%s<strong>”</strong> on %s</p>”, $profile->status->message, $statusDate);
  133.         }
  134.         echo “<p><a href=\”?logout\”>Logout</a></p>”; ?>
  135.         <ul >
  136. <?php
  137.     foreach($contacts as $user_friend){
  138.      if(isset($user_friend['email'])){
  139. ?>
  140. <li ><img src=”yahoo1.png” width=”30″ height=”30″/>
  141. <div ><strong><?php echo $user_friend['name']['givenName']; ?></strong><br /><?php echo $user_friend['email'];?></div>
  142. </li>
  143. <?php }
  144.  }  ?>
  145. </ul>
  146.  <?php     }
  147.     ?>
  148.     <script type=”text/javascript”>
  149.       var Event = YAHOO.util.Event;
  150.       var _gel = function(el) {return document.getElementById(el)};
  151.       function handleDOMReady() {
  152.         if(_gel(“yloginLink”)) {
  153.           Event.addListener(“yloginLink”, “click”, handleLoginClick);
  154.         }
  155.       }
  156.       function handleLoginClick(event) {
  157.         // block the url from opening like normal
  158.         Event.preventDefault(event);
  159.         // open pop-up using the auth_url
  160.         var auth_url = _gel(“yloginLink”).href;
  161.         PopupManager.open(auth_url,600,435);
  162.       }
  163.       Event.onDOMReady(handleDOMReady);
  164.     </script>
  165.   </body>
  166. </html>