SOAP web service using PHP + Mysql


Introduction:

This post for people those who are facing trouble with my last article “How to create SOAP service?”. These days web service is playing vital role in most of the web or mobile based application, where cross platform application used to connect and share data using web service. I will explain with some simple steps to do this stuff.

  Download



Step 1:

Create a server page called soap_server.php into http://localhost/soapserver/. Paste the below code into the soap_server.php file.



// nosoap.php library file inside your lib/ directory
require_once('lib/nusoap.php');

$server = new nusoap_server;

//$server ->configureWSDL('server', 'urn:server');
//$server ->wsdl->schemaTargetNamespace = 'urn:server';
//$server ->register('pollServer', array('value' => 'xsd:string'), array('return' => 'xsd:string'), 'urn:server', 'urn:server#pollServer');


//register a function that works on server
 $server->register('getInfo');

 // create age calculation function
 function find_age($birthday)
 { 
    list($byear, $bmonth, $bday) = explode('-', $birthday);
   list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
 
   $cday -= $bday;
   $cmonth -= $bmonth;
   $cyear -= $byear;
 
   if($cday < 0)
   $cmonth--;
   if($cmonth < 0)
   $cyear--;
 
   return $cyear;
 }

 // create the function 
 function getInfo($name, $birthday)
 {
    $result['status'] = true;

    if(!$name){
      return new soap_fault('Client','','SANJAY!');
    }


    // Return if you would like to check server response else delete this line.
    return $result = array('name'=> $name,'age'=> find_age($birthday) );

    

    $conn = mysql_connect('localhost','root','');
    mysql_select_db('webservice', $conn);

    $sql = "SELECT * FROM books";
    $q = mysql_query($sql);

    $result = array();

    while($row = mysql_fetch_array($q)) {

       $result[] = array(
                    'cd'=>$row['cd'],
                    'title'=>$row['title'],
                    'author'=>$row['author'],
                    'publisher'=>$row['publisher']
        );

    }

   return $result;
 }

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);
exit();



Step 2:

Now let us create a page called soap_client.php and paste below code to call soap server.



require_once('lib/nusoap.php');
header('Content-type: text/html');

$client = new nusoap_client('http://localhost/soapserver/soap_server.php');
$err = $client->getError();

if ($err) {

 echo '

Constructor error

' . $err . '

'; } $param = array( 'name' => 'Sanjoy Dey','birthday'=>'1987-12-20'); $response = $client->call('getInfo',$param); var_dump($response); if($client->fault) { echo "FAULT: Code: (".$client->faultcode.") "; echo "String: ".$client->faultstring; } else { echo $response['name']."\n Age: ".$response['age']."'s"; } echo '<h2> Request</h2> <>' . htmlspecialchars($client-&gt;request, ENT_QUOTES) . '</br> '; echo '<h2> Response</h2> <br>' . htmlspecialchars($client-&gt;response, ENT_QUOTES) . '</br> '; //echo '<h2>Debug</h2><br>' . htmlspecialchars($client-&gt;debug_str, ENT_QUOTES) . '</br>';

Step 3:

Go to browser and run http://localhost/soapserver/soap_client.php file. You will Soap Response as "Name" and "Date of Birth".

Conclusion:

This small post help you to create basic SOAP web service using PHP and nusoap.php library. Hope this post helps to solve displaying blank page. Keep visiting and stay updated. You can also join our technical groups by clicking below links.

Good Luck!

How to Generate Random number on Page load using jquery ?


How to Generate Random Numbers on Every Time page loads using Jquery ?

In my previous post I had shown you “Cross site ajax call”. Today I have an interesting topic. I am going to write about "Generating random numbers using jquery on everytime page reload."

Load jquery.js file into your webpage and paste below code into the script tag.

 


<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

<script type="text/javascript">

$(function () {
    
     var numMin =  '345';
     var numMax = '26654';
     
     var adjustedHigh = (parseFloat(numMax) - parseFloat(numMin)) + 1;
     
     
     var numRand = Math.floor(Math.random() * adjustedHigh) + parseFloat(numMin);
     
     
     if ((IsNumeric(numMin)  && (IsNumeric(numMax)) && (parseFloat(numMin) <= parseFloat(numMax )) && (numMin != '') && (numMax != ''))) {
         $("#randomnumber").val('DTKT'+numRand);
     }
});

function IsNumeric(n){
    return !isNaN(n);
}

</script>


<input type="text" name="txtTicketId" id="randomnumber" />

That's it you are done. Now every time you reload your page, you will get random generated number concatenate with string. You also can set your min and max range for random numbers, with variables numMin and numMax.

Hope this post is helpful to you. Keep visiting and if it is helpful to you then please do share with your friends and also you can join our technical network in facebook, Linkedin etc. with the link available bottom of the site.

Thank you all. All the best.

Cross site Ajax Request


            How to request data from a server in a different domain?

                  In my previous post I had shown you “How to create watermark for pdf using php  script ?”. Today I am going to write about jquery cross site ajax call to retrieve data from different domain. We can solve this using ‘JSONP’.
Let us know first “ What is JSONP ? “

 JSONP

JSONP is JSON with padding. JSONP is a technique that allows you to transfer JSON data across multiple domains. For security reasons browser does not allow script from remote domain to run. We are going to use JSONP to solve this. Cross domain ajax refers to the idea of making requests across domains in opposition to the same origin restriction. Padding or prefix  is typically name of callback function. The response to the JSONP is not json and not parsed as json also, It is javascript expression which invokes a function call on some json formatted data.
How is it works ?

It’s makes sense when used with script tag. For each new JSONP request browser add a new <script> tag or use existing one. The url request pointed to by the <script>’s src attribute returns JSON data, with a function call wrapped around it.


You can follow below script to do ajax request to cross site. For client side jquery –

$.ajax({

          dataType: ‘jsonp’,
          url : ‘http://www.example.com/getuserdetails’,
          data: ‘userid=204’,
          jsonp: ‘js_callback’,
          success: function() {
            // Do your stuffs on
           alert(“Successfully requested cross domain with jquery ajax ”);
          }
});


Php script given below :

function getuserdetails() {

       $data = array();
       $data  = getuserDataBYID($_GET[‘userid’]);
       echo $_GET[‘js_callback’].”(”.json_encode($data).”);”;

}

         Jsonp is fastest and easiest way to get json data from remote servers with javascript. It allowing including script tags from remote servers allows the remote servers to inject any content into a website. So if the remote servers hae vulnerabilities that allow javascript injection. So in that way it’s increased the risk also.



Hope this post will help you all to know about cross domain ajax request using JSONP callback. Keep visiting for new interesting posts here and please join my groups in linkedin, facebook to keep up to date. Please share your ideas here and do post if you have any new things to share with everyone. If you like my post please leave a comment here. All the best. Have a good day ahead.



You also can join my group for latest technology updates in below link,
To join in LinkedIn :
http://www.linkedin.com/groups?about=&gid=4300612


To Join in Google+ :

To follow us in twitter :
https://twitter.com/#!/myinfoplace1 





Create watermark for pdf using php ?


                                 Create watermark for pdf in php ?
       
                           Today I am writing about watermark for pdf. If you want to create watermark for your pdf then you can follow below code. In my previous posts I have shown you how to generate pdf using your own helper file. I have used mpdf and dom-pdf to generate pdf. So here I am going to show you “ How to generate pdf with watermark “.
Just add below code to generate pdf with watermark.
Method 1 :
<?php
//Generate pdf using mpdf
                $obj_mpdf = new mPDF();
                $obj_mpdf ->SetWatermarkText(“ Sample Watermark”);
                $obj_mpdf ->watermark_font = “Font Name”;
                $obj_mpdf ->showWatermarkText = true;

If You want to add image as your watermark then use below line

$obj_mpdf ->SetWatermarkImage(“/image/personal.jpg ”);
$obj_mpdf ->showWatermarkImage = true;
            $obj_mpdf ->WriteHTML(“ Your HTML Part ”);
?>
Method 2:
You can create a div and set the image for the div. using style sheet make your image opticity 0.1. Have a look on below code.
<style type=”text/css”>
          #watermark { position: fixed; bottom: 0px; right: 0px; width: 180px; height: 180px; opacity: .1; }
</style>
<div id="watermark"><img src="personal.jpg" width="100%"></div>

   Hope this post will help you to create watermark for your pdf. Keep visiting for new posts here. All the best. Have a good day. 





How to write SOAP web service using PHP?


  
     How to write web service using SOAP in PHP?
              
             In my previous post I had shown you “how to read gmail inbox using PHP”. Today I am writing my web service using SOAP. If you are wondering “How to create SOAP service?” , Then solution is here. Here I have created web service. All you need to do is, you just have to call service and function to perform particular task.

So let’s follow steps to do this stuffs.

 [NB: If you are facing trouble with below code then please do visit my latest updated post "SOAP web service using PHP". ]

Step 1 : Download nusoap zip file from here.  And paste it inside your www folder if you are using wamp, for xampp user paste it inside htdocs/xampp folder.
Step 2:  create two file call server.php and client.php.
Step 3 :  Inside server.php write below lines of code.
<?php
require_once('lib/nusoap.php');
//require("Connection.class.php"); 
$server = new nusoap_server;
//$server ->configureWSDL('server', 'urn:server');
//$server ->wsdl->schemaTargetNamespace = 'urn:server';
//$server ->register('pollServer', array('value' => 'xsd:string'), array('return' => 'xsd:string'), 'urn:server', 'urn:server#pollServer');

//register a function that works on server
$server ->register('getfeedDetails', array('value' => 'xsd:string'), array('return' => 'xsd:string'), 'urn:server', 'urn:server# getfeedDetails');




// create the function to fetch Data’s from Database
function getfeedDetails ()
{
              $conn = mysql_connect('localhost','root','');
                mysql_select_db('news', $conn);
                $sql = "SELECT * FROM user_story";
                $q = mysql_query($sql);
                       $items = array();
                while($row = mysql_fetch_array($q)){

                                $items [] = array(
                                                        'story_url'=>$row['story_url'],
                                                        'story_title'=>$row['story_title'],
                                                        'story_description'=>$row['story_description'],
                                                        'story_image'=>$row['story_image']
                                    );
                }
                      return $items;

}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);
?>
         That’s it you have created your server file to access and fetch details from database.
Step 4:    Now create client.php and inside it just  write below code. Create client object and call your server function to retrieve details.
<?php
require_once('lib/nusoap.php');
$url = "http://localhost/testserver/server.php?wsdl";
$client = new nusoap_client($url);
//Call server function
$response = $client ->call(' getfeedDetails ');

if($client->fault)
{
                echo "FAULT: <p>Code: (".$client ->faultcode.")</p>";
                echo "String: ".$client->faultstring;
}
else
{
                $result = $response;
                $count = count($result);
?>
    <table >
    <tr>
                <th>Story Url</th>
                <th>Story Title</th>
                <th>Story Description</th>
                <th>Story Image</th>
    </tr>
    <?php

    for($i = 0;$i < $count-1;$i++) {
                  $rowtype = ($i % 2) ? "style='background:#88DAEB'": "style=background:#FFF";
        ?>
    <tr <?php echo $rowtype; ?>>
                <td><?php echo $result[$i]['story_url']?></td>
                <td><?php echo $result[$i]['story_title']?></td>
                <td><?php echo $result[$i]['story_description']?></td>
                <td><img src="<?php echo $result[$i]['story_image']?>" type="photo"></td>
    </tr>
    <?php
                }
                ?>
    </table>
    <?php
}
 ?>
<style type="text/css">
    th {
        background:#007F99;
        color:#fff;
    }
</style>

?>
Step 5:   That’s it you have done. Now run your client.php in your browser. It will call server and fetch the details from database.  
So today I have shown you how to use simple SOAP webservice and to get details from database.  
    Thats all run the code and enjoy.Hope this post will help you tocreating simple webservice using SOAP. Post your queries if you have or anything  please share. Keep visiting for new posts here.
All the best. Have a good day. 


You also can join my group for latest technology updates in below link,
To join in LinkedIn :
http://www.linkedin.com/groups?about=&gid=4300612


To Join in Google+ :

To follow us in twitter :
https://twitter.com/#!/myinfoplace1 


google-site-verification: google32bdc2edc89dff15.html

Announcement from APPSNTECH.COM

                                    Hi Guys I am little busy with my work these days and unable to post articles. I will try to post some interesting and real time apps. I have drafted few articles and about to post. Currently I am busy with own PHP MVC Framework. It is almost done with basic functionality and about to add few more features to make it much more enjoyable.

Hope you all like my posts, If so please posts your comments here and share, if you want me to explain any specific topic and also you are welcome to share your ideas here. Just write an email to me I will post it with your name.

                                                 Thank you all my visitors,
                                            You will see my new post soon.


How will you read your Inbox messages using PHP script ?


Introduction

In my previous post i talked about “How to create your own helper file to generate PDF in PHP(CodeIgniter)?”. In some application may require you to code to read your email. If you are wondering “How to read your inbox messages using PHP script?”, then you are at right place. In this short article we will discuss about how to read messages from Gmail inbox using php script. We will make use of IMAP to read GMail inbox messages.

We will create a php file naming GmailReader.php and paste below code.

Below compact code to read email from your gmail account.



function readMail() {

    $dns = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
    $email = "Your Mail";
    $password = "Password";

    $openmail = imap_open($dns,$email,$password ) or die("Cannot Connect ".imap_last_error());
    if ($openmail) {

        echo  "You have ".imap_num_msg($openmail). " messages in your inbox";

        for($i=1; $i <= 100; $i++) {

            $header = imap_header($openmail,$i);
            echo "
"; echo $header->Subject." (".$header->Date.")"; } $msg = imap_fetchbody($openmail,1,"","FT_PEEK"); /* $msgBody = imap_fetchbody ($openmail, $i, "2.1"); if ($msgBody == "") { $portNo = "2.1"; $msgBody = imap_fetchbody ($openmail, $i, $portNo); } $msgBody = trim(substr(quoted_printable_decode($msgBody), 0, 200)); */ echo $msg; imap_close($openmail); } else { echo "Failed reading messages!!"; } }

That's all. We are done. Now run your GmailReader.php file from the browser and can see the results.

I am able to read gmail inbox using above code. Hope this post helps. Please consider sharing with friends, like the post, that way it will be helpful for others too. Keep visiting.

Create your own helper file to generate PDF in PHP(Codeigniter)


  How to write your own helper file to export grid as PDF in PHP?

                     In my previous post was about “How to generate PDF using PHP”. Today I am writing my own helper file for PDF generation. If you are wondering “How to create your own helper file to generate PDF in PHP(Codeigniter) ?” , Then solution is here. Here I have created single helper file for PDF to export any grid. All you need to do is, you just have to call my helper file and pass your datas as parameter into the function, That’s all done. It will generate PDF as well as you can print PDF file. By doing this you can reuse your code and you don’t have to write much lines of codes. So let’s follow steps to do this stuffs,

 

Step 1:

Download files from dom-pdf and m-pdf and extracts it into your helper folder, ie: /system/helpers/dompdf (or mpdf ).

Step 2:

Now create your own helper and name it pdfexport_helper.php and paste the below lines of code. If you are using mpdf then use below code.




/*
* Subject          : Export pdf using mpdf
* Author           : Sanjoy Dey
* @Created Date    : 10-02-2012
* Version          : CodeIgniter_2.0.3
*
*/

if ( ! function_exists('exportMeAsMPDF')) {

    function exportAsMPdf($htmView, $fileName) 
    {

        $CI =& get_instance();
        $CI->load->library('mpdf51/mpdf');
        // $CI->mpdf=new mPDF('c','A4','','',32,25,27,25,16,13);
        $CI->mpdf->AliasNbPages('[pagetotal]');
        $CI->mpdf->SetHTMLHeader('{PAGENO}/{nb}', '1',true);
        $CI->mpdf->SetDisplayMode('fullpage');
        $CI->mpdf->pagenumPrefix = 'Page number ';
        $CI->mpdf->pagenumSuffix = ' - ';
        $CII->mpdf->nbpgPrefix = ' out of ';
        $CI->mpdf->nbpgSuffix = ' pages';
        $CI->mpdf = new mPDF('', 'A4', 0, '', 12, 12, 10, 10, 5, 5);
        $style = base_url().'/source/template/css/stylesheet.css';
        $stylesheet = file_get_contents( $style);
        $CI->mpdf->WriteHTML($stylesheet,1);                       
        $CI->mpdf->WriteHTML($htmView,2);                       
        $CI->mpdf->Output('mpdf.pdf','I');
     }
  }

If you are using dompdf then use below code.

 
  
/*
* Subject          : Export pdf using dompdf
* Author           : Sanjay
* Version          : CodeIgniter_2.0.3
*/

if ( ! function_exists('exportMeAsDOMPDF')) {

     function exportAsDomPdf($htmView, $fileName) 
     {

         $CI =& get_instance();
         $CI->load->helper(array('dompdf', 'file'));
         $CI->load->helper('file');
         $pdfName = $fileName;
         $pdfData = pdf_create($htmView, $pdfName);
         write_file('Progress Repost', $pdfData);   
     }
}

?>
 
 
Step 3:

Open your controller page and inside your function write below code.



 #Export Function goes here#
 /*This Function is used for Exporting Pdf
  * Author : Sanjay
  */

  $this->load->helper(‘pdfexport_helper.php’);
  $urlId  = $this->uri->segment('3');

    if($urlId == "export") {

       $data['pageTitle'] = "Annual Report";
       $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);
       $templateView  = $this->load->view('../template_export',$data,TRUE);
       exportAsMPdf($templateView,$data['filename']);     
          OR          
       exportAsDomPdf($htmView,$fileName)                                                                 
    }

/* Export Pdf END here */

Step 4:

That’s all you have done all steps. Click in export button to export to PDF and enjoy.

Hope this post will help you a lot to reuse your code and creating your own helper file to generate PDF in PHP(Codeigniter).

Post your queries if you have and share. Keep visiting for new posts here. All the best. Have a good day.

You also can join my group for latest technology updates in below link,

How to generate pdf in PHP ?


  How to export grid data’s as PDF using PHP (Codeigniter)?

                   
  Today I have a new article for you all here. In my last post you saw major difference between ASP & ASP.NET. Today I am going to show you how to export grid datas as PDF using php. There is lots of plug-ins available to generate PDF in PHP. Here I am going to show you two best PDF generator which I used for my professional field.  I am well versed with dom-pdf and m-pdf. These two PDF generators really great I found compare to other. So here I am going to show you  “ How to export grid data as PDF in PHP ? “  
All you have to do first is you have to download dom-pdf or m-pdf zip files. If you are wondering where can you get the zip files then here is the links to download dom-pdf and m-pdf.  These are the steps you need to follow to generate PDF using dompdf and mpdf.
        Step 1:
                After downloading the zip files just extract it.  You’ll get a folder (I renamed it “dompdf” / “mpdf”), and put the whole thing into your helper folder, ie: /system/helpers/dompdf
       Step 2:
              Create plug-in for the dompdf. I have created plug-in and named it dompdf_helper.php and write below lines of code inside the file.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function 
pdf_create($html$filename=''$stream=TRUE
{
    
require_once("dompdf/dompdf_config.inc.php");
    
    
$dompdf = new DOMPDF();
    
$dompdf->load_html($html);
    
$dompdf->render();
    if (
$stream{
        $dompdf
->stream($filename.".pdf");
    
else {
        
return $dompdf->output();
    
}
}
?> 
Or



<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function 
pdf_create($html$filename=''$stream=TRUE
{
   require_once("dompdf/dompdf_config.inc.php");    spl_autoload_register(“DOMPDF_autoload”);   
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream{
        $dompdf
->stream($filename.".pdf");
    
else {
        
return $dompdf->output();
    
}
}
?>
          For m-pdf extracted folder into your library folder.

Step 3 :
            That’s it you have done almost. Now to call your dompdf helper file use a function in your controller to generate PDF file. Here is the code you need to write,
  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

  function exportPDF() {
     $this->load->helper(array('dompdf''file'));
     
// page info here, db calls, etc.     
     
$html $this->load->view('controller/viewfile'$datatrue);
     
pdf_create($html'filename');
     or
     
$data pdf_create($html''false);
     
write_file('name'$data);
     
//if you want to write it to disk and/or send it as an attachment   
   }
Or
    /* You can write your function like this also if you have separate view file to generate pdf */
function exportPDF() {
$year = $this->input->post(“currentyear”);
$monthname = $this->input->post(“month”);
$data[‘reportList’] = $this->pdfgenerator_model->getpdfDetails($id,$month,$year);
$dataView = $this->load-> view(‘pdf/report’,$data,true);
$this->load->helper(array('dompdf''file'));
$this->load->helper('file'));
      $pdfName = $monthname.”-”.$year.” 'Report'”;
      $pdfData = pdf_create($dataView,$pdfName);
      Monthnamewrite_file('My Monthly Report' ,$pdfData);
}    
?>
And If you want to use mpdf then it’s easy to generate. Here is the line of code to generate PDF using mpdf.
<?php
function generatePdf() {
$this->load->library(“mpdf51/mpdf”);
$data[‘reportList’] =$this->pdfgenerate_model ->getDetails();
$htmview = $this->load-> view(“pdfview”,$data,true);
$CI->mpdf = new mPDF('', 'A4', 0, '', 12, 12, 10, 10, 5, 5);
$this->mpdf->WriteHTML('<p>Hello There</p>',2);
$this->mpdf->Output(); 
}
?>
Step 4:
           That’s all you have done all steps. Click in export button to export to PDF and enjoy.

          This is how i generate PDF in PHP. Hope this post will help you a lot. Please do share and post your comments here. And If you have queries and if you want me to discuss then Please post your comments here. In my next post i will show you how to write your own helper file to generate PDF. So that you don't have to write much line of code, only you need to do is call helper and pass parameters to that. All the best. Have a good day.





Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions