Tuesday, September 11, 2012

facebook login using php and get user emai id and orther data from face book





stp-1->include_once(COMMONINCLUDES.'classes/facebook.php');
--------------------------------------------------------------------------
stp-2
------------------------------------------------------------------------
class facebookapi {
   
   
    function facebookapi($postArr)
    {       
        global $g_criteria1;
       
        parent :: CommonClass();
        //parent :: Facebook();

       
               
        $this->CheckGetMagicQuotes($postArr);
       
        switch($g_criteria1)
        {
           
            case "nu":
                $this->News_Update();
            break;
           
            case "tm":
                $this->Testimonial();
                               
           
            case "fcall":
                $this->Facebook_Site_Callback();
           
           
            case "flogin":
                $this->Facebook_Login();
               
            case "fus":
                $this->Facebook_Save_User();
               
               
            default:
                $this->Facebook_Login();
        }
    }
   
   
    /*==============================================
        Author     :     bikash rajan nayak
        Modified By :  bikash rajan nayak
        Date    :    Nov 03, 2011
        Function to display home page
    ===================================================*/   
   
   
   
    function News_Update()
    {
   
        $smarty = new Smarty;
        $smarty->compile_check = true;
        $smarty->debugging = false;   
       
        $trail = new Trail();
        $trail->addStep('News & Update');
        $smarty->assign('TPL_PAGE_TITLE', 'News & Update');
       
        $plan_list_Order = $this->GetHomePlanList_Order_Two();
        $smarty->assign('TPL_PLAN_LIST_ORDERBY', $plan_list_Order);
       
        $news_list = $this->GetNEWS_List('I');
       
        $smarty->assign('TPL_NEWS_LIST', $news_list);
               
        $smarty->assign_by_ref('trail', $trail->path);
        $smarty->display('news-and-update.tpl');
    }
   
    function Facebook_Site_Callback()
    {
   
        $smarty = new Smarty;
        $smarty->compile_check = true;
        $smarty->debugging = false;   
               
        $hidArr = array();
        $hidArr = $this->GetHiddenVarVal($this);       
                                   
                   
                   
                   
                                $facebook = new Facebook(array('appId'  => '17378553343966053114','secret' => '63bb9447a4cf7df7d4be985bs55a6df3b648a9d',));
                                // Get User ID
                                $user = $facebook->getUser();
                               
                                if ($user)
                                {
                                try
                                {
                               
                                // Proceed knowing you have a logged in user who's authenticated.
                                    $user_profile = $facebook->api('/me');
                                   
                                   
                                        $Fuid = $user_profile['id'];
                                        $smarty->assign('FACE_UID',$Fuid);
                                       
                                        $FemailID = $user_profile['email'];
                                        $smarty->assign('FACE_EMAILID',$FemailID);
                                       
                                        $FfirstName = $user_profile['first_name'];
                                        $smarty->assign('FACE_FirstName',$FfirstName);
                                       
                                        $FlastName = $user_profile['last_name'];
                                        $smarty->assign('FACE_LastName',$FlastName);
                                       
                                        if(isset($user_profile['gender']))
                                        {
                                            $Fgender = $user_profile['gender'];
                                            $smarty->assign('FACE_gender',$Fgender);
                                        }
                                       
                                    //echo '<pre>'; print_r($user_profile); exit;
                                                                       
                                    //session_destroy();
                                                                       
                                        $u_selquery = "SELECT
                                                                    fld_id
                                                            FROM
                                                                            tbl_user
                                                            WHERE 
                                                                    fld_email = '$FemailID' AND flogin ='$Fuid' ";            
                                           
                                   
                                    $u_queryexe = mysql_query($u_selquery);
                                    if(mysql_affected_rows() > 0)
                                    {
                                       
                                                                               
                                        $whrCls1 = " WHERE (fld_email='$FemailID') AND flogin ='$Fuid' ";
                                        $table_fields1 = array('fld_id', 'fld_userName',  'fld_firstName', 'fld_lastName', 'fld_status', 'flogin');
                                        $sql_sel1 = $this->buildSelectSQL('tbl_user', $table_fields1, $whrCls1);
                                        $rs_valid1 = @mysql_query($sql_sel1);
                                       
                                            if($rs_valid1 && @mysql_num_rows($rs_valid1) > 0)
                                                {
                                               
                                                    $row = @mysql_fetch_assoc($rs_valid1);
                                                    $user_name = $row['fld_userName'];
                                                    $id = $row['fld_id'];
                                                    $fullName = $row['fld_firstName'];
                                                    $email = $FemailID;
                                                   
                                                    $facebookId = $row['flogin'];
                                                   
                                                    $objSessions = new Sessions($user_name, $id, 'customer', $fullName, $facebookId , '', $email);
                                                    $objSessions->set_sessions();
                                                   
                                                    //$_SESSION['facebookId'] = $facebookId;
                                                   
                                                   
                                                    //echo "<pre>";print_r($_SESSION);
                                                    //exit;

                                                 
//$logoutUrl = $facebook->getLogoutUrl();
//header("Location: $logoutUrl");
                                                    $this->redirectPage('myaccount.php?event=myaccount', $hidArr);   
                                                    exit;
                                                               
                                                               
                                                }
                                                else
                                                {
                                                    $hidArr = 'user name alrady exist, please choose another user name';
                                                    $this->redirectPage('myaccount.php?event=myaccount', $hidArr);   
                                                    exit;
                                               
                                                }
                   
                                   
                                    }
                                    else
                                    {
                                   
                                   
                                    //$logoutUrl = $facebook->getLogoutUrl();
                                    //header("Location: $logoutUrl");

                                    //$smarty->display('facebook-login.tpl');
                                    //exit;
                                    //07-March-Work............................................................................
                                   
                                   
                                        $Fuid = $user_profile['id'];
                                        $smarty->assign('FACE_UID',$Fuid);
                                       
                                        $FemailID = $user_profile['email'];
                                        $smarty->assign('FACE_EMAILID',$FemailID);
                                       
                                        $FfirstName = $user_profile['first_name'];
                                        $smarty->assign('FACE_FirstName',$FfirstName);
                                       
                                        $FlastName = $user_profile['last_name'];
                                        $smarty->assign('FACE_LastName',$FlastName);
                                       
                                        if(isset($user_profile['gender']))
                                        {
                                            $Fgender = $user_profile['gender'];
                                            $smarty->assign('FACE_gender',$Fgender);
                                        }
                                   
//echo "hello1";
//exit;   

                                    if($Fuid != '' && $FemailID != '' && $FfirstName != '' && $FlastName != '' )
                                    {
                                   
                                            $defaultImage = '2011_1.gif';
                                           
                                            $tbl_fld = array(
                                            'fld_userName', 'fld_email', 'fld_firstName', 'fld_lastName',
                                            'fld_sex', 'fld_image', 'fld_profileView','fld_wishView',
                                            'fld_status' ,'fld_creationDate','flogin' 
                                            );
                                            $tbl_fld_val = array(   
                                            $FemailID, $FemailID,  $FfirstName, $FlastName,
                                            $Fgender, $defaultImage, '1' , '1',
                                            '1', date('Y-m-d H:i:s'), $Fuid    
                                            );
                                           
                                            $sql_ins = $this->buildManipSQL('tbl_user', $tbl_fld, $tbl_fld_val, 'IN');
                                            $rs = mysql_query($sql_ins);
                                            $fld_id = mysql_insert_id();
                                           
                                           
                                            if($rs &&  $fld_id!='')
                                            {   
                                                    $whrCls1 = " WHERE (fld_userName ='".$FemailID."' OR fld_email='".$FemailID."') AND flogin='$Fuid'";
                                                    $table_fields1 = array('fld_id', 'fld_firstName', 'fld_lastName', 'fld_status');
                                                    $sql_sel1 = $this->buildSelectSQL('tbl_user', $table_fields1, $whrCls1);
                                                    $rs_valid1 = @mysql_query($sql_sel1);
                                                   
                                                    if($rs_valid1 && @mysql_num_rows($rs_valid1) > 0)
                                                        {
                                                           
                                                            $row = @mysql_fetch_assoc($rs_valid1);
                                                            $user_id = $row['fld_id'];
                                                           
                                                            if($row['fld_status'] == 0)
                                                            {                   
                                                                $hidArr['ec'] = NOT_ACT;                   
                                                                $hidArr['am'] = "YES";
                                                                $this->redirectPage('login.php', $hidArr);
                                                                exit;
                                                            }
                                                            else
                                                            {
                                                           
                                                                $user_name = $FemailID;
                                                                $id = $row['fld_id'];
                                                                $fullName = $row['fld_firstName'];
                                                                $email = $FemailID;
                                                                $objSessions = new Sessions($user_name, $id, 'customer', $fullName, '', '', $email);
                                                                $objSessions->set_sessions();
                                                                //echo "<pre>";print_r($_SESSION);
                                                                $this->redirectPage('myaccount.php?event=myaccount', $hidArr);   
                                                                exit;                   
                                                            }               
                                                        }
                                                   
                                           
                                            }
                               
                                   
                                    }
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                   
                                    }
                               
                                }
                                catch (FacebookApiException $e)
                                {
                                error_log($e);
                                $user = null;
                                }
                                }
                               
                               
                               
                                // Login or logout url will be needed depending on current user state.
                                if ($user) {
                               
                               
                                $logoutUrl = $facebook->getLogoutUrl();
                               
                                } else
                                {
                                    $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
                                    //echo '<script>self.location = '.$loginUrl.';
                                    header("Location: $loginUrl");
                                        //$hidArr['ec'] = " ";
                                        //$this->redirectPage($loginUrl, $hidArr);
                                }
                               
       
               
       
       
    }
   
   
   
   
   
   
   
   
   

    function Facebook_Login()
    {
        $smarty = new Smarty;
        $smarty->compile_check = true;
        $smarty->debugging = false;   
       
       
       
       
       
       
       
        $facebook = new Facebook(array('appId'  => '1737324242385966053114','secret' => '63bb9447a4cf7df7d4be985b3s6s53a2db648a9d',));

        // Get User ID
        echo "hjjdfgljf";
        $user = $facebook->getUser();
        if ($user) {
          try {
            // Proceed knowing you have a logged in user who's authenticated.
            $user_profile = $facebook->api('/me');
          } catch (FacebookApiException $e) {
            error_log($e);
            $user = null;
          }
        }
    //echo '<pre>'; print_r($user_profile); exit;
       
        $Fuid = $user_profile['id'];
        $smarty->assign('FACE_UID',$Fuid);
       
        $FemailID = $user_profile['email'];
        $smarty->assign('FACE_EMAILID',$FemailID);
       
        $FfirstName = $user_profile['first_name'];
        $smarty->assign('FACE_FirstName',$FfirstName);
       
        $FlastName = $user_profile['last_name'];
        $smarty->assign('FACE_LastName',$FlastName);
       
        $Fgender = $user_profile['gender'];
        $smarty->assign('FACE_gender',$Fgender);
       
        //echo '<pre>'; print_r( $user_profile); exit;
        //echo "<pre>"; print_r($_SESSION); exit;   
        //echo $facebook->getLogoutUrl();
       
       
        $cmsPageContent = $this->GetHomeCMSPage(1);
        $pageUrl = $this->getPageURLString();
        $smarty->assign('MENU_SEL',$pageUrl);
       
        //echo $cmsPageTitle = $cmsPageContent[0]['id'];
        $cmsPageTitle = $cmsPageContent[0]['title'];
        $cmsPageContent = $cmsPageContent[0]['content'];
       
        $smarty->assign('TPL_CMS_PAGE_TITLE', $cmsPageTitle);
        $smarty->assign('TPL_CMS_PAGE_CONTENT', $cmsPageContent);
               
       
       
       
        //echo "<pre>"; print_r($cmsPageContent); exit;
        //$smarty->assign('TPL_PLAN_LIST_ORDERBY', $plan_list_Order);
       
       
        $eventSlider = $this->GetUserEventSlider();
        $smarty->assign('event_list', $eventSlider);   
        //echo "<pre>";    print_r($eventSlider);exit;
               
        $smarty->display('facebook-login.tpl');
       
       
       
    }
   
   
   
    function Facebook_Save_User()
    {
   
        $smarty = new Smarty;
        $smarty->compile_check = true;
        $smarty->debugging = false;
       
        $hidArr = array();
        //$hidArr = $this->GetHiddenVarVal($this);
       
        $status = '0';       
        $ipaddress=$_SERVER['REMOTE_ADDR'];   
       
               
        //echo "<br />";
         date('Y-m-d H:i:s');
        //exit;
        $defaultImage = '2011_1.gif';
               
         if($this->hidface_gender == 'male')
         {
             $sex = '1';
         }
         else
         {
             $sex = '0';
         }
       
       
         if($this->txtemailID != '')
        {
            $u_selquery = "SELECT
                                fld_id
                         FROM
                                 tbl_user
                        WHERE 
                                fld_userName = '$this->txtUserName' OR  fld_email = '$this->txtemailID' ";            
       
         $u_queryexe = mysql_query($u_selquery);
         if(mysql_affected_rows() > 0)
             {
                $hidArr['ec'] = 'User Name or Email ID already exit Plz choose another name';
                $this->redirectPage('sign-up.php?event=ur', $hidArr);
            }
         }   
       
               
       
       
         if($this->hidface_emailid != '' && $this->hidface_fname != '' && $this->hidface_lname != '' && $this->hidface_gender != '' && $this->txtUserName != ''
            && $this->txtPassword != ''
            )
        {
         
       
            $defaultImage = '2011_1.gif';
            $tbl_fld = array(
                                'fld_userName', 'fld_email', 'fld_password', 'fld_firstName', 'fld_lastName',
                                'fld_sex', 'fld_image', 'fld_profileView','fld_wishView','fld_ipAddr',
                                'fld_status' ,'fld_creationDate','flogin' 
                            );
            $tbl_fld_val = array(   
                                    $this->txtUserName, $this->hidface_emailid,  md5($this->txtPassword), $this->hidface_fname, $this->hidface_lname,
                                    $sex, $defaultImage, '1' , '1',  $ipaddress,
                                    '1', date('Y-m-d H:i:s'), $this->hidface_id    
                                );
           
            $sql_ins = $this->buildManipSQL('tbl_user', $tbl_fld, $tbl_fld_val, 'IN');
            $rs = mysql_query($sql_ins);
            $fld_id = mysql_insert_id();
                               
            if($rs)
            {   
           
                 $txt_pass = md5($this->txtPassword);
            if($this->txtUserName != '' && $fld_id != '')
            {
           
                       
               $whrCls1 = " WHERE (fld_userName ='".$this->txtUserName."' OR fld_email='".$this->hidface_emailid."') AND fld_password='$txt_pass'";
               $table_fields1 = array('fld_id', 'fld_firstName', 'fld_lastName', 'fld_status');
                 $sql_sel1 = $this->buildSelectSQL('tbl_user', $table_fields1, $whrCls1);
       
           
            $rs_valid1 = @mysql_query($sql_sel1);
            if($rs_valid1 && @mysql_num_rows($rs_valid1) > 0)
            {
               
                $row = @mysql_fetch_assoc($rs_valid1);
                $user_id = $row['fld_id'];
               
                if($row['fld_status'] == 0)
                {                   
                    $hidArr['ec'] = NOT_ACT;                   
                    $hidArr['am'] = "YES";
                    $this->redirectPage('login.php', $hidArr);
                    exit;
                }
                else
                {
               
                    $user_name = $this->txtUserName;
                    $id = $row['fld_id'];
                    $fullName = $row['fld_firstName'];
                    $email = $this->txtUserName;
                    $objSessions = new Sessions($user_name, $id, 'customer', $fullName, '', '', $email);
                    $objSessions->set_sessions();
                    echo "<pre>";print_r($_SESSION);
                    $this->redirectPage('myaccount.php?event=myaccount', $hidArr);   
                    exit;                   
                }               
            }
           
        }   
            }
            else
            {
                $hidArr['ec'] = USER_ADD_FAIL;
                $this->redirectPage('sign-up.php?event=ur', $hidArr);
            }
             }
        else
        {

            $hidArr['ec'] = MEND_FIELDS;
            $this->redirectPage('sign-up.php?event=ur', $hidArr);
            exit;
        }
       
    }

 }
---------------------end face book class--------------------------------------------

last step pass user request for login
include_once('classes/facebookapi.class.php');

$obj_Facebookapi = new facebookapi($_REQUEST); 


session start headers already sent error

please add the top of the page below these code
-----------------------------------------------
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

ob_start();
session_cache_expire(30);
session_start();

Sunday, September 9, 2012

Create a simple Web Service Using PHP, MySQL,JSON, and , XML

Web services are taking over the world. I credit Twitter's epic rise to the availability of a simple but
rich API. Why not use the same model for your own sites? Here's how to create a basic web
 service that provides an XML or JSON response using some PHP and MySQL.

The PHP / MySQL

copy/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

  /* soak in the passed variable or set our own */
  $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; 
//10 is the default
  $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; 
 //xml is the default
  $user_id = intval($_GET['user']); //no default

  /* connect to the db */
  $link = mysql_connect('localhost','username','password') or die('Cannot 
   connect to the DB');
  mysql_select_db('db_name',$link) or die('Cannot select the DB');

  /* grab the posts from the db */
  $query = "SELECT post_title, guid FROM wp_posts WHERE post_author = 
  $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
  $result = mysql_query($query,$link) or die('Errant query:  '.$query);

  /* create one master array of the records */
  $posts = array();
  if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
      $posts[] = array('post'=>$post);
    }
  }

  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
  }
  else {
    header('Content-type: text/xml');
    echo '<posts>';
    foreach($posts as $index => $post) {
      if(is_array($post)) {
        foreach($post as $key => $value) {
          echo '<',$key,'>';
          if(is_array($value)) {
            foreach($value as $tag => $val) {
              echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
            }
          }
          echo '</',$key,'>';
        }
      }
    }
    echo '</posts>';
  }

  /* disconnect from the db */
  @mysql_close($link);
}
With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.
Take the following sample URL for example:
copyhttp://mydomain.com/web-service.php?user=2&num=10
Now, we can take a look at the possible results of the URL.

The XML Output

copy<posts>
  <post>
    <post_title>SSLmatic SSL Certificate Giveaway Winners</post_title>
    <guid>http://davidwalsh.name/?p=2304</guid>
  </post>
  <post>
    <post_title>MooTools FileManager</post_title>
    <guid>http://davidwalsh.name/?p=2288</guid>
  </post>
  <post>
    <post_title>PHPTVDB: Using PHP to Retrieve TV Show Information</post_title>
    <guid>http://davidwalsh.name/?p=2266</guid>
  </post>
  <post>
    <post_title>David Walsh: The Lost MooTools Plugins</post_title>
    <guid>http://davidwalsh.name/?p=2258</guid>
  </post>
  <post>
    <post_title>Create Short URLs Using U.Nu</post_title>
    <guid>http://davidwalsh.name/?p=2218</guid>
  </post>
  <post>
    <post_title>Create Bit.ly Short URLs Using PHP</post_title>
    <guid>http://davidwalsh.name/?p=2194</guid>
  </post>
  <post>
    <post_title>Represent Your Repositories Using the GitHub Badge!</post_title>
    <guid>http://davidwalsh.name/?p=2178</guid>
  </post>
  <post>
    <post_title>ZebraTable</post_title>
    <guid>http://davidwalsh.name/?page_id=2172</guid>
  </post>
  <post>
    <post_title>MooTools Zebra Table Plugin</post_title>
    <guid>http://davidwalsh.name/?p=2168</guid>
  </post>
  <post>
    <post_title>SSLmatic: Quality, Cheap SSL Certificates and Giveaway!</post_title>
    <guid>http://davidwalsh.name/?p=2158</guid>
  </post>
</posts>
Take this next sample URL for example:
copyhttp://mydomain.com/web-service.php?user=2&num=10&format=json
Now, we can take a look at the possible results of the URL.

The JSON Output

copy{"posts":[{"post":{"post_title":"SSLmatic SSL Certificate Giveaway Winners",
 "guid":"http:\/\/davidwalsh.name\/?p=2304"}},
 {"post":{"post_title":"MooTools FileManager",
 "guid":"http:\/\/davidwalsh.name\/?p=2288"}},
 {"post":{"post_title":"PHPTVDB: Using PHP to Retrieve TV Show Information", 
"guid":"http:\/\/davidwalsh.name\/?p=2266"}}, 
{"post":{"post_title":"David Walsh: The Lost MooTools Plugins", 
"guid":"http:\/\/davidwalsh.name\/?p=2258"}},
 {"post":{"post_title":"Create Short URLs Using U.Nu",
 "guid":"http:\/\/davidwalsh.name\/?p=2218"}}, 
{"post":{"post_title":"Create Bit.ly Short URLs Using PHP","guid":
 "http:\/\/davidwalsh.name\/?p=2194"}},{"post":{"post_title":
 "Represent Your Repositories Using the GitHub Badge!","guid":
 "http:\/\/davidwalsh.name\/?p=2178"}},{"post": 
{"post_title":"ZebraTable","guid":"http:\/\/davidwalsh.name\/?page_id=2172"}}, 
{"post":{"post_title":"MooTools Zebra Table Plugin","guid": 
"http:\/\/davidwalsh.name\/?p=2168"}},
 {"post":{"post_title":"SSLmatic: Quality, 
Cheap SSL Certificates and Giveaway!", 
"guid":"http:\/\/davidwalsh.name\/?p=2158"}}]}

what is soap service in php example with php




The Soap Web services platform is XML and HTTP request. XML provides a language which can be used between different platforms and programming languages. The HTTP protocol is the most used Internet protocol. Web services platform elements are SOAP (Simple Object Access Protocol), UDDI (Universal Description, Discovery and Integration), WSDL (Web Services Description Language).
Here I have talking about SOAP, NuSOAP and how it will use in PHP with example. So now let's start. Simple Object Access Protocol (SOAP) is a simple XML-based protocol to let applications exchange information over HTTP.  Today's Web Service (SOAP) is most popular and it provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.
Actually, the SOAP API itself has not been deprecated-- just some of the functions. NuSOAP is a PHP library that allows you to send and receive SOAP messages. NuSOAP is a group of PHP classes that allow developers to create and consume SOAP services. It does not require any special PHP extensions. To use NuSOAP You must download NuSOAP library. Click Here to download library first.
Once you have downloaded a library file, you simply need to place it in your code tree so that you can include it from your PHP code. For my examples, I placed it in the same directory as the sample code itself.
I will start with the ubiquitous "Hello, World" example. This will demonstrate the basic coding of NuSOAP clients and servers.
I am going to start with the server code. The server exposes a single SOAP method named "Hello", which takes a single string parameter for input and returns a string. Hopefully, the comments within the code provide sufficient explanation. For example server.php is a file name.
<?php

 // include NuSOAP class for service call
 require_once('nusoap.php');
 // Create the server instance
 $server = new soap_server;

 // Register the method to expose
 $server->register('hello');

  // Define the method as a PHP function
  function hello($name) 
  {
   return 'Hello, ' . $name; 
  }

  // Use the request to (try to) invoke the service
  $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? 
               $HTTP_RAW_POST_DATA : '';

  $server->service($HTTP_RAW_POST_DATA);

?>
Now create a client side Script which will save it to the file clients.php. There are a few important things to note. First, when the instance of soap client is created, the parameter specified is the URL to the service. Second, when calling the service, the first parameter is the service name. This must match with the method registered within server.php. Finally, the second parameter in the call is an array of parameters that will be passed to the SOAP service method. Since the hello method of server.php requires a single parameter, this array has one element.
<?php
 
 // Pull in the NuSOAP code
 require_once('nusoap.php');
 // Create the client instance
 $client = new nusoap_client('http://localhost/xml-webservice/server.php');
 // Check for an error
 $err = $client->getError();

 if ($err) 
 {
     // Display the error
     echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
     // At this point, you know the call that follows will fail
 }

 // Call the SOAP method
 $result = $client->call('hello', array('name' => 'Scott'));

 // Check for a fault 
 if ($client->fault) 
 {
      echo '<h2>Fault</h2><pre>';
      print_r($result);
      echo '</pre>';
 }
  else
  {
    
  // Check for errors
      $err = $client->getError();
      if ($err) 
  {
          // Display the error
          echo '<h2>Error</h2><pre>' . $err . '</pre>';
      }
   else 
   {
          // Display the result
          echo '<h2>Result</h2><pre>';
          print_r($result);
       echo '</pre>';
      }
 }
?>
NuSOAP also provides a debug information. Adding the following to the client code will display this  debugging information.
/// Display the debug messages
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
I showed above code how  to display the SOAP request and response. Here is what the request from the client..php looks like.
Result

Hello, Scott

Request

POST /xml-webservice/server.php HTTP/1.0 
 Host: localhost  
User-Agent: NuSOAP/0.7.3 (1.114)  
Content-Type: text/xml; charset=ISO-8859-1  
SOAPAction: ""  
Content-Length: 500    
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1564:hello xmlns:ns1564="http://tempuri.org">
<name xsi:type="xsd:string">Scott</name>
</ns1564:hello></SOAP-ENV:Body></SOAP-ENV:Envelope>

Response

HTTP/1.1 200 OK  
Date: Tue, 29 Sep 2009 08:47:02 GMT  
Server: Apache/2.2.3 (Win32) DAV/2 mod_ssl/2.2.3 OpenSSL/0.9.8d mod_autoindex_color PHP/5.2.0
X-Powered-By: PHP/5.2.0  
X-SOAP-Server: NuSOAP/0.7.3 (1.114)  
Content-Length: 518  
Connection: close  
Content-Type: text/xml; charset=ISO-8859-1    
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body><ns1:helloResponse xmlns:ns1="http://tempuri.org">
<return xsi:type="xsd:string">Hello, Scott</return>
</ns1:helloResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
You can CLICK HERE full source code 

Saturday, September 8, 2012

simple create capcha code using php

<?php
session_start();

/*
* File: CaptchaSecurityImages.php
* Author: bikash ranjan nayak
* Copyright: 2012 bikash

* Updated: 07/09/12
* Requirements: PHP 4/5 with GD and

class CaptchaSecurityImagesbybikash {

    var $font = &#039;monofont.ttf&#039;;

    function generateCode($characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = &#039;23456789bcdfghjkmnpqrstvwxyz&#039;;
        $code = &#039;&#039;;
        $i = 0;
        while ($i generateCode($characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 20, 40, 100);
        $noise_color = imagecolorallocate($image, 100, 120, 180);
        /* generate random dots in background */
        for( $i=0; $i&lt;($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $ifont, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this-&gt;font , $code) or die('Error in imagettftext function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['security_code'] = $code;
    }

}

$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) &amp;&amp; $_GET['characters'] &gt; 1 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImagesbybikash($width,$height,$characters);

?>

<img src="/wp-content/themes/avd/CaptchaSecurityImages.php?width=162&amp;height=45&amp;characters=5" />

Friday, September 7, 2012

how to send email with attachment file php

<?php
$fileatt = "ptkt.docx"; // Path to the file
$fileatt_type = "application/docx"; // File Type
$fileatt_name = "ptkt.docx"; // Filename that will be used for the file as the attachment

$email_from = "bikash@nayak.com"; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for bikash my blog http://phptechnicalgroups.blogspot.in.
";
$email_message .= "Thanks for bikash.
"; // Message that the email has in it

$email_to = 'bikash@techwave.com'; // Who the email is to

$headers = "From: ".$email_from;

$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message .= "\n\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";

$ok = @mail($email_to, $email_subject, $email_message, $headers);

if($ok) {
echo "you mail has sent with attchment";

} else {
die("smtp not connecting");
}
?>

paypal pro recurring payment method implement in php



1 step-> create a paypalconfig.php
----------------------------------------------------------------------------
<?php
class paypal_pro
{
    public $API_USERNAME;
    public $API_PASSWORD;
    public $API_SIGNATURE;
    public $API_ENDPOINT;
    public $USE_PROXY;
    public $PROXY_HOST;
    public $PROXY_PORT;
    public $PAYPAL_URL;
    public $VERSION;
    public $NVP_HEADER;
    public $CURLEMPTYCHECK=FALSE;
   
    function __construct($API_USERNAME, $API_PASSWORD, $API_SIGNATURE, $PROXY_HOST, $PROXY_PORT, $IS_ONLINE = FALSE, $USE_PROXY = FALSE, $VERSION = '57.0')
    {
   
        $this->API_USERNAME = $API_USERNAME;
        $this->API_PASSWORD = $API_PASSWORD;
        $this->API_SIGNATURE = $API_SIGNATURE;
        $this->API_ENDPOINT = 'https://api-3t.paypal.com/nvp';
        $this->USE_PROXY = $USE_PROXY;
        if($this->USE_PROXY == true)
        {
            $this->PROXY_HOST = $PROXY_HOST;
            $this->PROXY_PORT = $PROXY_PORT;
        }
        else
        {
            $this->PROXY_HOST = '127.0.0.1';
            $this->PROXY_PORT = '808';
        }
        if($IS_ONLINE == FALSE)
        {
            $this->PAYPAL_URL = 'https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=';
        }
        else
        {
            $this->PAYPAL_URL = 'https://www.paypal.com/webscr&cmd=_express-checkout&token=';
        }
        $this->VERSION = $VERSION;
    }

    function hash_call($methodName,$nvpStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$this->API_ENDPOINT);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        if($this->USE_PROXY)
        {
            curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST.":".$this->PROXY_PORT);
        }
        $nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->VERSION)."&PWD=".urlencode($this->API_PASSWORD)."&USER=".urlencode($this->API_USERNAME)."&SIGNATURE=".urlencode($this->API_SIGNATURE).$nvpStr;
        curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
        $response = curl_exec($ch);
        $nvpResArray=$this->deformatNVP($response);
        $nvpReqArray=$this->deformatNVP($nvpreq);
        $_SESSION['nvpReqArray']=$nvpReqArray;
        if (curl_errno($ch))
        {
            $this->CURLEMPTYCHECK=TRUE;
   
        }
        else
        {
            curl_close($ch);
        }

    return $nvpResArray;
    }

    function deformatNVP($nvpstr)
    {

        $intial=0;
        $nvpArray = array();
        while(strlen($nvpstr))
        {
            $keypos= strpos($nvpstr,'=');
            $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
            $keyval=substr($nvpstr,$intial,$keypos);
            $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            $nvpArray[urldecode($keyval)] =urldecode( $valval);
            $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
         }
        return $nvpArray;
    }

    function __destruct()
    {

    }
}
?>
----------------------end cofig class--------------------------------------

2 step-> indclude paypalconfig.php where you input user information.
if(isset($_REQUEST['paynow'])){
require_once("paypal_pro.inc.php");
$firstName =urlencode( $_POST['firstName']);
$lastName =urlencode( $_POST['lastName']);
$creditCardType =urlencode( $_POST['creditCardType']);
$creditCardNumber = urlencode($_POST['creditCardNumber']);
$expDateMonth =urlencode( $_POST['expDateMonth']);
$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);
$expDateYear =urlencode( $_POST['expDateYear']);
$cvv2Number = urlencode($_POST['cvv2Number']);
$address1 = urlencode($_POST['address1']);
$address2 = urlencode($_POST['address2']);
$city = urlencode($_POST['city']);
$state =urlencode( $_POST['state']);
$zip = urlencode($_POST['zip']);
$amount = urlencode($_POST['amount']);
$currencyCode="USD";
$paymentAction = urlencode("Sale");
 $carderrormsg="";


    $profileStartDate = urlencode(date('Y-m-d h:i:s'));
    $billingPeriod = urlencode($_POST['billingPeriod']);// or "Day", "Week", "SemiMonth", "Year"
    $billingFreq = urlencode($_POST['billingFreq']);// combination of this and billingPeriod must be at most a year
    $initAmt = $amount;
    $failedInitAmtAction = urlencode("ContinueOnFailure");
    $desc = urlencode("Recurring $".$amount);
    $autoBillAmt = urlencode("AddToNextBilling");
    $profileReference = urlencode("Anonymous");
    $methodToCall = 'CreateRecurringPaymentsProfile';
    $nvpRecurring ='&BILLINGPERIOD='.$billingPeriod.'&BILLINGFREQUENCY='.$billingFreq.'&PROFILESTARTDATE='.$profileStartDate.'&INITAMT='.$initAmt.'&FAILEDINITAMTACTION='.$failedInitAmtAction.'&DESC='.$desc.'&AUTOBILLAMT='.$autoBillAmt.'&PROFILEREFERENCE='.$profileReference;


$nvpstr='&PAYMENTACTION='.$paymentAction.'&AMT='.$amount.'&CREDITCARDTYPE='.$creditCardType.'&ACCT='.$creditCardNumber.'&EXPDATE='.         $padDateMonth.$expDateYear.'&CVV2='.$cvv2Number.'&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$address1.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&COUNTRYCODE=US&CURRENCYCODE='.$currencyCode.$nvpRecurring;


//$paypalPro = new paypal_pro('nayakr.bikash@gmail.com', 'QFZCW5555N5HZM8VBG7Q', 'A.d9eRKfd1yVkRrtmMfCFLTqa655555M9AyodL0SJkh55555YztxUi8W9pCXF6.4NI', '', '', FALSE, FALSE );

$resArray = $paypalPro->hash_call($methodToCall,$nvpstr);
echo "<pre>";print_r($resArray ) ;