RSS

Category Archives: PHP

How to Create a Custom Facebook Share Button for your iFrame Tab

A common feature of Facebook is the use of being able to ‘Share’ objects whether these objects are videos or links. If you’re anything like us then you like to have full control over what and how you share it, this proved rather difficult until now. In this tutorial we are going to show you, in two easy steps, how to create a custom Facebook ‘Share’ button to use on your Facebook iFrame tab that will allow viewers to share and post your custom content to their Wall. The difference between this ‘Share’ button and the standard ‘Share’ button is that every element (custom message, custom title and custom thumb image) within the share window is completely customizable, giving you total control over what you want to share.

The Code

Step 1: PHP

<source lan=’java’>
<?php
$title=urlencode('Title of Your iFrame Tab');
$url=urlencode('http://www.facebook.com/wordpressdesign');
$summary=urlencode('Custom message that summarizes what your tab is about, or just a simple message to tell people to check out your tab.');
$image=urlencode('http://www.yourdomain.com/images/share-thumbnail.jpg');
?>
</source>

Each line within the PHP allows you customize every element within the share window. Every bit of coding within the “(‘…‘)” that you see effects those elements. To understand which PHP element affects what, take a look at the screenshot below:
fb share gragh
Keep note that the $url section must contain a URL. This directs people to your tab once the share has been published on the poster’s wall. Also, the $image must contain a full URL. If your link to the image is “images/share-thumbnail.jpg”, it will not be read correctly because the share window is coming from Facebook’s server, not yours. As for the size of your thumbnail image ($image), it will automatically be proportionately resized to fit either 100px wide or 100px tall (depending which measurement is larger of the original image). So ideally, you should make your thumbnail 100px X 100px to prevent unwanted resizing.

Step 2: XHTML

<source lan=’java’>
<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&amp;p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Insert text or an image here.</a>
</source>

As you can see, the onClick=”window.open(‘…’);” will create a popup window that contains the ‘Share’ information (see picture above). Do not change this information. The only bits of coding you need to change are the width and the height of the code (if you are not satisfied with the measurements). These measurements define the width and height of the popup window containing the “Share” information.

The other bit of coding you can change is where it says; “Insert text or an image here”. This is where you can insert whatever element you choose to become the link. This can simply be text or a fancy button that you created yourself. The choice is up to you!

Completed Code

<source lan=’java’>
<?php
$title=urlencode('Title of Your iFrame Tab');
$url=urlencode('http://www.facebook.com/wordpressdesign');
$summary=urlencode('Custom message that summarizes what your tab is about, or just a simple message to tell people to check out your tab.');
$image=urlencode('http://www.yourdomain.com/images/share-thumbnail.jpg');
?>

<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&amp;p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Insert text or an image here.</a>
</source>

Demo

You can view the live demo here.
Download the code here.

Please Note

Your iFrame tab must be a PHP file in order for this to work.

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible.

 
Leave a comment

Posted by on May 16, 2012 in PHP

 

How to remove index.php in Codeigniter URL

By default, the index.php file will be included in your URLs:

example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:


<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]</code>

In the above example, any HTTP request other than those for index.php, images, and robots.txt is treated as a request for your index.php file.

 
Leave a comment

Posted by on January 25, 2012 in CodeIgniter

 

A Quick Code Igniter and JQuery Ajax Tutorial

This tutorial assumes a basic working knowledge of Code Igniter. If you have never used CI before, please refer to the framework documentation

In the old days (2 years ago), working the Javascript magic to create a cool AJAX based event took a fairly decent working knowledge of the mechanisms behind the process.

With the increasing popularity of Javascript libraries however, this type of functionality became available to the web site hobbyist, and was made much easier for the web site professional.

The following step-by-step tutorial will show you how to combine the power of JQuery (a javascript library that weighs in at about 20k) with Code Igniter (a PHP framework based on the MVC design pattern) to quickly and painlessly pass a record ID through the javascript and over to the server, where it will be passed to a mysql database, used to retrieve some data, and sent back to the page for display.

Step 1
We begin by assuming that you have a div with an id of content, which is where you would like your freshly retrieved data to display, once it has been freshly retrieved. For this exercise, you have already taken an action to call your javascript function with a record ID parameter.

The first thing you need to do, is make sure JQuery is being loaded, and to create a function for your AJAX request.

Step 2:
Next, youll use the JQuery function load, and attach it to your content div:

function get_record_id(record_id) {
     $('#content').load()
}

Step 3:
The load function accepts three arguments. The page to be called on the other side of the HTTPRequest, the array to pass through the POST, and a callback function. It looks like this:

function get_record_id(record_id) {
     $('#content').load(/controller/method,p,function(str){

	 });
}

Lets go back to that. Code Igniter URLs are created by calling the name of your controller, followed by the function inside the controller class that will handle your request. If your server does not support mod-rewrite, you may also need to append an index.php to the beginning. The str inside the callback function is the results of your AJAX request. There isnt much use for the str when using the .load function, but it does come in handy using the other JQuery AJAX functions – $.post and $.get, which I assume are self explanatory.

Step 4

var p = {}; //instantiate the array
p[record_id] = record_id //assign your record_id variable to it.

Thats all there is to it. Your final javascript function looks like this:

function get_record_id(record_id) {
     var p = {};
     p[record_id] = record_id
     $('#content').load(/controller/method,p,function(str){

     });
}

Step 5
On the CI side, you have a controller and method setup something like this:

class Controller
{
   function Controller()
   {
       parent::CI;
   }

   function method()
   {
   }
}

The important part is the method() function, as it will contain some of the code we need to make things happen.

Step 6
The first thing you need to do on the CI side is retrieve the value passed through the request object. This is simple enough, using $_POST[record_id]. You also want to load up your database model so you can get the record out of your database. So, well load the database library, and then load the actual model. Then, we want to send the record ID to the database, get the resulting data, and pass it back out to the request. our function starts to look like its doing something useful pretty quickly.

function method()
{
   $record_id = $_POST[record_id];
   //set the record ID
   $this->load->library(database);
   //load the database library to connect to your database
   $this->load->model(records);
   //inside your system/application/models folder, create a model based on the procedure
   //outlined in the CI documentation
   $results = $this->records->get_record($record_id);
   //get the record from the database
}

Step 7
At this point, we need to go into our records.php file in the model folder. Since Code Igniter uses a Model-View-Controller structure, database activity, server-side processing, and client-side display should be as separate from one another as possible. You dont NEED to do this for Code Igniter to do its thing, but its good practice.

Inside the records.php file, well create a method called get_record to match the method referenced above. Well use it to get a record by its primary key of ID, put the resulting data into an array, and send it back to the controller, out to the view, and ultimately into the content div we started with.

function get_record($record_id)
{
   $this->db->where(ID,$record_id);
   //we want the row whose ID matches the value were passing in
   $query = $this->db->get(record_table);
   //get the table and put it into an object named $query
   $row = $query->row();
   //gets the first row of the resulting dataset.  In this case, only 1 row will ever be returned
   $results[record][$row->ID][name] = $row->name;
   //here, we create a multi-dimensional array holding the returned values
   //based on the key.
   return $results;
   //send the record back to the controller
}

The trickiest part of this section is the array. It seems pretty complex from here, but youll see soon enough how it breaks down into something more manageable as we go along.

Step 8
Were back to the controller again, and we have one more line to add – this time to pass the resulting data into a view to be formatted and printed to the content div. The whole method() function now looks like this:

function method()
{
   $ID = $_POST[record_id];  //set the record ID
   $this->load->library(database);
   //load the database library to connect to your database
   $this->load->model(records);
   //inside your system/application/models folder, create a model based on
   //the procedure outlined in the CI documentation
   $results = $this->records->get_record($record_id);
   //get the record from the database
   $this->load->view(AJAX_record,$results);
}

Step 9
The AJAX_record.php file should be in your system/application/views folder. Keep in mind, that when you pass an array to a view (in this case the $results array), it will be exploded inside the view. So, the path to your record is now $record, instead of $results[record]. Also inside will be your standard HTML markup, and something like this:

< ?php foreach($record as $id=>$value) { ?>
     The name associated with this record is: < ?php print $value[name];?>
< ?php } ?>

This output is what php is sending to the request object, and is also what gets loaded into the content div. Code Igniter and JQuery make it that easy to dynamically load data using AJAX.

Referenced by: http://www.mrforbes.com/blog/2009/01/a-quick-code-igniter-and-jquery-ajax-tutorial/

 
5 Comments

Posted by on March 2, 2011 in CodeIgniter, JQuery, jQuery for PHP, PHP

 

Developing Web Services Using PHP

A web service consists of a server to serve requests to the web service and a client to invoke methods on the web service. The PHP class library provides the SOAP extension to develop SOAP servers and clients and the XML-RPC extension to create XML-RPC servers and clients. Before I delve further into developing web services with PHP, I shall briefly discuss web services.

Introduction to Web Services

A web service is a software system designed for interoperable interaction over a network. A web service is defined with a WSDL (Web Services Description Language) document, and other systems interact with the web service using SOAP messages, transferred using HTTP with an XML serialization. A web service is an abstract resource that provides a set of functions and is implemented by an agent, which sends and receives messages. A provider entity provides the functionality of a web service with a provider agent and a requester entity uses the web service functionality with a requester agent. Web services implement various technologies, some of which are XML, SOAP, and WSDL. XML is a standard format for data exchange. Web service requests and responses are sent as XML messages. The elements and attributes that may be specified in an XML document are specified in an XML Schema. SOAP provides a standard framework for packaging and exchanging XML messages. WSDL is an XML document in the http://schemas.xmlsoap.org/wsdl/ namespace for describing a web service as a set of endpoints operating on messages. A WSDL document specifies the operations (methods) provided by a web service and the format of the XML messages.

Installing the PHP Web Services Extensions

The SOAP and XML-RPC extensions are packaged with the PHP 5 installation. The SOAP extension and the XML-RPC extension are not enabled by default in a PHP installation. To enable the SOAP and XML-RPC extensions add the following extension directives in the php.ini configuration file.

extension=php_xmlrpc.dll
extension=php_soap.dll

Restart the Apache 2 server to activate the SOAP and XML-RPC extensions. The SOAP extension supports subsets of the SOAP 1.1, SOAP 1.2, and WSDL 1.1 specifications.

Creating a SOAP Web Service

After activating the SOAP extension in the PHP configuration file, a SOAP server and a SOAP client may be created using the SOAP PHP class library. A SOAP server serves web service requests and a SOAP client invokes methods on the SOAP web service. The SOAP library provides various functions for creating a SOAP server and a SOAP client. Some of the commonly used SOAP functions are discussed in Table 1.

Table 1. SOAP functions

Method Description
SoapServer->__construct( mixed wsdl [, array options] ) Creates a SoapServer object. The wsdl parameter specifies the URI of the WSDL. SoapServer options such as SOAP version may be specified in the options array.
SoapServer->addFunction( mixed functions ) Adds one or more PHP functions that will handle SOAP requests. A single function may be added as a string. More than one function may be added as an array.
SoapServer->fault() SoapServer fault indicating an error.
SoapServer->getFunctions() Returns a list of functions.
SoapServer->handle() Processes a SOAP request, invokes required functions and sends back a response.
SoapServer->setClass(string class_name [, mixed args [, mixed ...]] ) Sets the class that will handle SOAP requests. Exports all methods from the specified class. The args are used by the default class constructor.
SoapHeader->__construct() Creates a SOAP header.
SoapClient->__soapCall( string function_name, array arguments [, array options [, mixed input_headers [, array &output_headers]]] ) Invokes a SOAP function.
SoapClient->__doRequest() Performs a SOAP request.
SoapClient->__getFunctions() Returns a list of SOAP functions.
SoapClient->__getTypes() Returns a list of SOAP types.

Creating a SOAP Server

Before we create a SOAP server we need to create a WSDL document defining the web service. The WSDL document defines the operations that the web service provides. I will create an example web service that provides an operation getCatalogEntry, which returns a catalog entry for a catalog ID. A WSDL is an XML document in the http://schemas.xmlsoap.org/wsdl/ namespace. Some of the elements of a WSDL document are discussed in Table 2.

Table 2. WSDL elements

Element Description
definitions Root element of a WSDL document.
types Specifies data type definitions for the messages exchanged by the web service. XML Schema is the recommended type system.
message Defines the data being transmitted. A message consists of one or more parts. A part is associated with a type.
portType Defines a set of operations and the input-output messages for each operation.
operation An action (method) supported by the service. Each operation consists of input and output messages.
input Specifies a message format for the request.
output Specifies a message format for the response.
binding Defines message format and protocol details for operations and messages for a particular portType.
service Specifies a group of ports.
port Defines an endpoint by associating an address with a binding.

Next, create a WSDL document for the example web service. The example WSDL document, catalog.wsdl, defines message elements getCatalogRequest and getCatalogResponse for the request and response messages. In the WSDL document define a portType, CatalogPortType, for the getCatalogEntry operation that returns a catalog entry as a HTML string for a string catalogId. Define a binding, CatalogBinding, for the getCatalogEntry operation and the input output messages. The soap:binding element specifies that the binding is bound to the SOAP protocol format. The soap:operation element specifies information for the operation. The soap:body element specifies how the message parts appear inside the SOAP Body element. Define a service CatalogService that consists of a port, CatalogPort, which is associated with the CatalogBinding binding. The soap:address element specifies the URI of an address. The catalog.wsdl WSDL document is listed below.

<?xml version ='1.0' encoding ='UTF-8' ?> 
<definitions name='Catalog' 
  targetNamespace='http://example.org/catalog' 
  xmlns:tns=' http://example.org/catalog ' 
  xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' 
  xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
  xmlns:soapenc='http://schemas.xmlsoap.org/soap/
  encoding/' 
  xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' 
  xmlns='http://schemas.xmlsoap.org/wsdl/'> 

<message name='getCatalogRequest'> 
  <part name='catalogId' type='xsd:string'/> 
</message> 
<message name='getCatalogResponse'> 
  <part name='Result' type='xsd:string'/> 
</message> 

<portType name='CatalogPortType'> 
  <operation name='getCatalogEntry'> 
    <input message='tns:getCatalogRequest'/> 
    <output message='tns:getCatalogResponse'/> 
  </operation> 
</portType> 

<binding name='CatalogBinding' type=
'tns:CatalogPortType'> 
  <soap:binding style='rpc' 
    transport='http://schemas.xmlsoap.org/soap/http'
  /> 
  <operation name='getCatalogEntry'> 
    <soap:operation soapAction='urn:localhost-catalog#
    getCatalogEntry'/> 
    <input> 
      <soap:body use='encoded' namespace=
      'urn:localhost-catalog' 
        encodingStyle='http://schemas.xmlsoap.org/soap
       /encoding/'/> 
    </input> 
    <output> 
      <soap:body use='encoded' namespace=
   'urn:localhost-catalog' 
        encodingStyle='http://schemas.xmlsoap.org/soap/
    encoding/'/> 
    </output> 
  </operation> 
</binding> 

<service name='CatalogService'> 
  <port name='CatalogPort' binding=
  'CatalogBinding'> 
    <soap:address location='http://localhost/
    soap-server.php'/> 
  </port> 
</service>
</definitions>

Copy the catalog.wsdl document to the C:\Apache2\htdocs directory, the directory in which PHP scripts are run. Create a PHP script, soap-server.php, to define the operations provided by the CatalogService web service. In the soap-server.php script define a function getCatalogEntry() that takes a catalogId as an argument and returns a string consisting of an HTML document. The HTML document string returned comprises of the catalog entry for the specified catalogId.

 

 

function getCatalogEntry($catalogId) { 
  if($catalogId=='catalog1')
          return "<HTML> … </HTML>";
elseif ($catalogId='catalog2')
return "<HTML>…</HTML>";

}

The WSDL cache is enabled by default. Disable the WSDL cache by setting the soap.wsdl_cache_enabled configuration option to 0.

ini_set("soap.wsdl_cache_enabled", "0");

Create a SoapServer object using the catalog.wsdl WSDL.

$server = new SoapServer("catalog.wsdl");

Add the getCatalogEntry function to the SoapServer object using the addFunction() method. The SOAP web service provides the getCatalogEntry operation.

$server->addFunction("getCatalogEntry");

Handle a SOAP request.

$server->handle();

The soap-server.php script is listed below.

<?php 
function getCatalogEntry($catalogId) { 
  if($catalogId=='catalog1')

return "<HTML>
 <HEAD>
  <TITLE>Catalog</TITLE>
 </HEAD
 <BODY>
<p> </p>
 <table border>
<tr><th>CatalogId</th>
<th>Journal</th><th>Section
</th><th>Edition</th><th>
Title</th><th>Author</th>
</tr><tr><td>catalog1</td>
<td>IBM developerWorks</td><td>
XML</td><td>October 2005</td>
<td>JAXP validation</td>
<td>Brett McLaughlin</td></tr>
</table>
</BODY>
</HTML>";

elseif ($catalogId='catalog2')

return "<HTML>
 <HEAD>
  <TITLE>Catalog</TITLE>
 </HEAD
 <BODY>
<p> </p>
 <table border>

<tr><th>CatalogId</th><th>
Journal</th><th>Section</th>
<th>Edition</th><th>Title
</th><th>Author
</th></tr><tr><td>catalog1
</td><td>IBM developerWorks</td>
<td>XML</td><td>July 2006</td>
<td>The Java XPath API
</td><td>Elliotte Harold</td>
</tr>
</table>
</BODY>
</HTML>";
} 

ini_set("soap.wsdl_cache_enabled", "0"); 
$server = new SoapServer("catalog.wsdl"); 
$server->addFunction("getCatalogEntry"); 
$server->handle(); 

?>

In the next section, I will create a SOAP client to send a request to the SOAP server.

Creating a SOAP Client

Create a PHP script, soap-client.php, in the C:\Apache2\htdocs directory. In the PHP script, create a SOAP client using the SoapClient class. The WSDL document, catalog.wsdl, is specified as an argument to the SoapClient constructor. The WSDL document specifies the operations that are available to the SOAP client.

$client = new SoapClient("catalog.wsdl");

Specify the catalogId for which a catalog entry is to be retrieved. Invoke the getCatalogEntry method of the SOAP web service.

$catalogId='catalog1';
$response = $client->getCatalogEntry($catalogId);

Output the response to the browser.

echo $response;

The soap-client.php script is listed below.

<?php  
  $client = new SoapClient("catalog.wsdl");
  $catalogId='catalog1';
  $response = $client->getCatalogEntry($catalogId);
  echo $response;
?>

Invoke the soap-client.php PHP script with the URL http://localhost/soap-client.php.The catalog entry for the catalog1 catalogId gets output as shown in Figure 1.

Invoking the SOAP client
Figure 1. Invoking the SOAP client

 

 

Creating an XML-RPC Web Service

XML-RPC is a specification and a set of implementations designed for applications to make remote procedure calls over the network. The remote procedure calls are made using HTTP as the transport and XML as the encoding.

Structure of an XML-RPC Request and Response

An XML-RPC message is an HTTP-POST request. The request body is in XML format. The request is sent to an XML-RPC server, which runs some business logic and returns a response in the form of XML. An example XML-RPC request is listed below.

POST /php/xmlrpc-server.php HTTP/1.0
User-Agent: Example Client
Host: localhost
Content-Type: text/xml
Content-length: 190

<?xml version="1.0"?>
<methodCall>
   <methodName>getCatalog</methodName>
   <params>
      <param>
         <value><string>catalog1
         </string></value>
         </param>
      </params>
   </methodCall>

The URI in the header, /php/xmlrpc-server.php specifies the server URI to which the request is sent. The HTTP version is also specified. The User-Agent and Host are required to be specified. The Content-Type is text/xml and the Content-Length specifies the content length.

The request body is in XML with root element as methodCall. The methodCall element is required to contain a sub-element methodName which specifies the name of the method to be invoked as a string. If the XML-RPC request has parameters, the methodCall element contains sub-element params. The params element contains one or more param elements. Each of the param elements contains a value element. The param value may be specified as a string, a Boolean, a four-byte signed integer, double-precision signed, floating point number, date/time, or base-64 encoded binary. The sub-element of value in which a param value is specified is different for different value types. If a type is not specified the default type is string. The sub-elements for the value types are listed in Table 3.

Table 3. Value elements

Value Type Element
ASCII String <string>
Four-byte signed integer <i4> or <int>
Boolean <boolean>
Double-precision signed or floating point number. <double>
Date/time <dateTime.iso8601>
Base-64 encoded binary. <base64>

A param value may also be of type <struct>. A <struct> element consists of <member> elements. Each <member> element contains a <name> element and a <value> element. An example of struct value is listed below.

<struct>
   <member>
      <name>catalogId</name>
      <value><string>catalog1
      </string></value>
      </member>
   <member>
      <name>journal</name>
      <value><string>IBM developerWorks
      </string></value>
      </member>
   </struct>

A value element in a member element may be of any of the param data types including struct. A param type may also be of type <array>. An <array> element consists of of a <data> element, which consists of one or more <value> elements. An example of an <array> param value is listed below.

<array>
   <data>
      <value><i4>1</i4></value>
      <value><string>IBM developerWorks
      </string></value>
      <value>XML</value>
      <value><string>Introduction to dom4j
      </string></value>
      <value><string>Deepak Vohra</string
      ></value>
      </data>
   </array>

A <value> element in a <data> element may consist of any of the data types including struct and array. The server response to an XML-RPC request is in the format of XML. An example response is listed below.

HTTP/1.1 200 OK
Connection: close
Content-Length: 190
Content-Type: text/xml
Date: 
Server: Example Server

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>Introduction 
         to SQLXML</string></value>
         </param>
      </params>
   </methodResponse>

If an error has not occurred, the server response returns “200 OK.” The Connection header specifies the state of the connection after the response is completed. For non-persistent connection the Connection header value is “close.” The Content-Type is text/xml. The response body is in XML format with root element as methodResponse. The methodResponse element consists of a single <params> element, which consists of a single <param> element. The <param> element contains a single <value> element.

Instead of a <params> element a methodResponse element may also consists of a single <fault> element. The <fault> element contains a <value> element, which contains a <struct> element with two <member> elements faultCode of type integer and faultString of type string. An example of a XML-RPC server response with a <<fault> element is listed below.

HTTP/1.1 200 OK
Connection: close
Content-Length: 190
Content-Type: text/xml
Date: 
Server: Example Server

<?xml version="1.0"?>
<methodResponse>
   <fault>
      <value>
         <struct>
            <member>
               <name>faultCode</name>
               <value><int>4</int
               ></value>
               </member>
            <member>
               <name>faultString</name>
               <value><string>No such Method.
               </string></value>
               </member>
            </struct>
         </value>
      </fault>
   </methodResponse>

Creating an XML-RPC Server

The PHP XML-RPC extension is a PHP implementation of the XML-RPC specification. The XML-RPC PHP class library provides functions to create a XML-RPC server and invoke methods on the server. Some of the commonly used XML-RPC functions are discussed in Table 4.

Table 4. XML-RPC PHP functions

Function
Description
xmlrpc_server_create ()
Creates an XML-RPC server
xmlrpc_encode_request ( string method, mixed params [, array output_options] )
Generates XML for a method request or response. Returns a string or FALSE on error.
xmlrpc_encode ( mixed value )
Generates XML for a PHP variable.
xmlrpc_decode_request ( string xml, string &method [, string encoding] )
Decodes XML into PHP. Returns an array.
xmlrpc_get_type ( mixed value )
Returns XML-RPC data types, for example “struct”, “int”, “string”, “base64″ for a PHP value.
xmlrpc_set_type ( string &value, string type )
Sets xmlrpc type, base64, or datetime for a PHP string value. Returns True or False on error.
xmlrpc_server_register_method ( resource server, string method_name, string function )
Registers PHP function to a web service method. The method_name value is the same as the value of the methodName element in the XML-RPC request.
xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options] )
Parses XML request and invokes method. Returns result of method call. The user_data parameter specifies any application data for the method handler function. The output_options parameter specifies a hashed array of options for generating response XML. The following options may be specified. output_type: Specifies output data type; “php” or “xml”. Default data type is “xml”. If output type is “php” other values are ignored. verbosity: Specifies compactness of generated message.escaping: Specifies if and how to escape some characters.version: Specifies version of XML to use. Value may be “xmlrpc”, “soap 1.1″ and “simple”. Version may also be set to “auto”, which specifies to use the version the request came in. encoding: Specifies the encoding of the data. Default is “iso-8859-1″.Example value of the output_options parameter is as follows.$output_options = array( “output_type” => “xml”, “verbosity” => “no_white_space”, “escaping” => array(“markup”, “non-ascii”, “non-print”), “version” => “xmlrpc”, “encoding” => “utf-8″ );
xmlrpc_is_fault ( array arg )
Determines if an array value represents XML-RPC fault.
xmlrpc_server_destroy ( resource server )
Destroys a server resource.
 

 

Create a PHP script, xmlrpc-webservice.php, in the C:/Apache2/htdocs directory. In the PHP script, define a function, hello_func. Any function that is invoked by a client is required to take three parameters: the first parameter is the name of the XML-RPC method invoked. The second parameter is an array containing the parameters sent by the client. The third parameter is the application data sent in the user_data parameter of the xmlrpc_server_call_method() function. In the hello_func function, retrieve the first parameter, which is a name sent by the client, and output a Hello message.

function hello_func($method_name, $params, $app_data)
{
$name = $params[0];
return "Hello $name.";
}

Create an XML-RPC server using the xmlrpc_server_create() method.

$xmlrpc_server=xmlrpc_server_create();

If a server does not get created the xmlrpc_server_create method returns FALSE. Register the hello_func function with the server using the xmlrpc_server_register_method method. The first argument to the xmlrpc_server_register_method method is the XML-RPC server resource. The second argument is name of the method that is provided by the web service, which is the <methodName> element value in a XML-RPC request. The third argument is the PHP function to be registered with the server.

$registered=xmlrpc_server_register_method 
($xmlrpc_server, "hello", "hello_func" );

If the PHP function gets registered, the xmlrpc_server_register_method returns TRUE.

Creating an XML-RPC Client

Next, I shall create a XML-RPC client to send a request to the XML-RPC server. First, specify the XML string to be sent in the request.

$request_xml = <<< END
<?xml version="1.0"?>
<methodCall>
    <methodName>hello</methodName>
      <params>
        <param>
          <value>
            <string>Deepak</string>
          </value>
        </param>
      </params>
<methodCall>
END;

To escape XML in PHP, <<<END ….END; is used. An XML document demarker other END may also be used. The methodCall element specifies the web service method that is to be invoked. Invoke the web service method using the xmlrpc_server_call_method function. The first argument to the xmlrpc_server_call_method function is the server resource. The second argument is the string containing the XML-RPC request. The third argument is the application data that is sent to the third parameter of the method handler function.

$response=xmlrpc_server_call_method( $xmlrpc_server, 
$request_xml, '', array(output_type => "xml"));

Output the XML-RPC response from the server.

print $response;

The PHP script, xmlrpc-webservice.php, is listed below.

<?php
function hello_func($method_name, $params, $app_data)
{
$name = $params[0];
return "Hello $name.";
}

$xmlrpc_server=xmlrpc_server_create();
$registered=xmlrpc_server_register_method 
($xmlrpc_server, "hello", "hello_func" );

$request_xml = <<< END
<?xml version="1.0"?>
<methodCall>
    <methodName>hello</methodName>
      <params>
        <param>
          <value>
            <string>Deepak</string>
          </value>
        </param>
      </params>
</methodCall>
END;
$response=xmlrpc_server_call_method( $xmlrpc_server, 
$request_xml, '', array(output_type => "xml"));
print $response;
?>

Copy the xmlrpc-webservice.php script to the C:/Apache2/htdocs directory. Invoke the PHP script with the URL http://localhost/xmlrpc-webservice.php. The response from the server gets output to the browser as shown in Figure 2.

Response From XML-RPC Web Service
Figure 2. Response from XML-RPC web service

To demonstrate an error in the request, returned as a <fault> element in the response XML, make the request XML not valid XML. For example replace </methodCall> with <methodCall> in the $request_xml. Invoke the xmlrpc-webservice.php. The response from the server is returned as a <fault> element that consists of a struct element value, which consists of faultCode and faultString members, as shown in Figure 3.

Response As fault Element
Figure 3. Response as fault element

References

For more information, see W3C’s WSDL page and SOAP Primer.

Deepak Vohra is a NuBean consultant and a web developer.

http://onlamp.com/pub/a/php/2007/07/26/php-web-services.html

 
1 Comment

Posted by on February 26, 2011 in PHP

 

CodeIgniter Explained

will you learn?

1. What is a PHP Framework?

2. What is CodeIgniter?

3. What is MVC?

4. MVC Pattern

5. Why CodeIgniter?


What is a PHP Framework?

First of all, what is PHP? I’d say that PHP (Hypertext Preprocessor) is the best scripting language at this moment, even if is exactly 15 years old. PHP is able to create dynamic webpages interpreted by a webserver (Apache, Lighttpd, nginx, etc), but also can create GUI applications.

This is enough for you right now, if you need more details check these links:

1. http://en.wikipedia.org/wiki/PHP

2. http://gtk.php.net

3. http://httpd.apache.org/

4. http://nginx.org/

5. http://www.lighttpd.net/

If you already know what is PHP we have to move on. If you’re already a PHP programmer, I think you know that some parts of your code are duplicated. So this is the moment to find out what is a PHP Framework.

A PHP Framework is a collection of pre-written methods and classes, that are already secured, optimized, well documented and ready to use anytime, “out of the box”.

What is CodeIgniter?

As you maybe think, CodeIgniter is a PHP Framework for PHP 4 and PHP 5 in the same time. CodeIgniter’s main goal is to allow user to develop lightning fast applications, without writing your code from zero. So you already have a basic package, with everything what’s needed to write a kick-ass application.

What is MVC?

MVC (Model-View-Controller), is an architectural pattern used in almost all programming and scripting languages, including PHP.

The Model – usually is used to connect with the database, making CRUD operations (Create, Read, Update, Delete)

The View – most of the time, here you will print the data received from your controller, and other HTML markup. Basically, a view is every page you see over the internet.

The Controller – is responsible to handle the requests, manipulating models or other controller. Try to keep the controller as simple as possible.

MVC Pattern

So, let me explain it a bit. There would be 5 steps:

1. Your computer will send a request to the Controller

2. The Controller will interact with the Model, making a demand.

3. The Model will make the processing, then return some data to the Controller.

4. The Controller will analyze the results (maybe needs some more data, and it will make another request to another Model).

5. Finally, the data will be sent to the view, which is interpreted by the webserver, and will be displayed back in your browser.

Let’s take an example over a registration page.

1. You enter on the registration page, complete the fields and click Submit.

2. The request is send to the controller, it will ask the model about your identity.

3. The model analyze the data you sent (if you are already a member, if your data is correct, etc.) and it will send an Accept or a Denial back to the controller.

4. The Controller will analyze the Accept/Denial from the model, and will decide what to do.

5. Finally, it will send “a Welcome” to the view, which will be visible to you as a Welcome page, or an error page.

Why CodeIgniter?

First of all, CodeIgniter has the MVC architecture. So your application will be organized as I’ve already explained.

Is very easy to learn, as it’s deeply documented and very easy to extend.

CodeIgniter is a very light PHP framework (2.1 MB including the entire documentation) compared with:

1. Zend Framework 1.10.2 Full – 24 MB

2. symfony 1.4.3 – 5.1 MB

3. CakePHP 1.2.6 – 4.5 MB

Is lightning fast compared with other PHP Framework, I think it’s the fastest PHP framework.

The installation process is very very easy, you only need to unpack latest stable version, upload it on your host ,simply set ONE parameter and you are done. If course if you need something more, you have a few config variables. We’ll talk about the installation is a future tutorial.

CodeIgniter doesn’t have a command line tool like CakePHP or symfony. Maybe some users will like the command line tool, because it will generate your models, views and controller and other stuff, but honestly I feel I am losing the control of such an application. Not everytime you will need a model or a view for your controller, so why generate them?

Maybe you were wondering “Why other frameworks are so big?”. Most of the frameworks have included in their core additional libraries (authentication, captcha, currency, feed, ajax, connection with webservices – Twitter, Flickr etc.), Object Relationship Mapper (we’ll talk about ORM in next tutorials) and other. A normal projects doesn’t need everything I’ve listed, so “why pay for what you don’t need”?

And I forgot to say, that CodeIgniter and other PHP Frameworks listed here are Open Source, so you can use them for free and modify then as you wish. There is a bunch of libraries, helpers and other open source software built on CodeIgniter.

Another thing I like to CodeIgniter is the way they help me building my links. What can you do when you want to move your application to another domain? Do you use relative paths to your files?

Do you create links with your domain everywhere and then mass-edit? Here CodeIgniter will help you with 2 methods: base_url() and site_url().

Both methods return the main URL for your application, but there’s a small difference between them, you’ll learn about this later. Let’s say you have your script installed on your-domain.com/my_blog, base_url() will return you exactly your URL.

CodeIgniter has also a fantastic form validation library, which helps you validate your data easily, before making database operations.

Sending emails has never been easier. CodeIgniter even has an email class for you. Do you want to send an email? Ok, here is the code:

$this->email->to("my_friend@example.com");
$this->email->from('me@example.com');
$this->email->subject('Hello from CodeIgniter');
$this->email->message('This is my first email from CodeIgniter.');
$this->email->send();

Want to send an attachment too? Add this line;

$this->email->attach('/relative/path/to/your/attachment.png');

And you’re done.

There are still much more tricks to discover, but this is enough for today.
Now you know what is PHP, what is a PHP Framework, what is CodeIgniter and why did I pick CodeIgniter.

This tutorial was like a simple intro to make you more familiar with PHP frameworks and especially with CodeIgniter, my favorite. Good luck and see you next time.

http://codeigniterdirectory.com/ – A directory where you may find a low of useful stuff regarding CodeIgniter

http://codeigniter.com/wiki – The official CodeIgniter Wiki

For more CodeIgniter tutorials, make sure you subscribe to our RSS feed. If you have any questions about CodeIgniter, feel free to leave a comment!

 
1 Comment

Posted by on December 21, 2010 in PHP

 

Configure WAMP for sending mail in remote mail server

This works for me and should work for you: Use Fake Sendmail and a webhost mail server (i.e. – Godaddy, 1and1, etc.).

1.) Download the sendmail zip and extract it to C:\Wamp\bin\sendmail (for purposes of this example). http://www.glob.com.au/sendmail/sendmail.zip

2.) Edit C:\wamp\bin\sendmail\sendmail.ini and set the following to your mail server’s requirements (mine are below):

smtp_server=mail.domainname.com
 smtp_port=25
 smtp_ssl=none
 ;default_domain=domainname.com
 auth_username=smtpuser@domainname.com
 auth_password=smtppassword
 ;pop3_server=
 ;pop3_username=
 ;pop3_password=
 force_sender= smtpuser@domainname.com
;force_recipient=
hostname=domainname.com

3.) Set the path of sendmail.exe in your php.ini file.


[mail function]
 ; For Win32 only.
 SMTP =

 ; For Win32 only.
 sendmail_from =

 ; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
 sendmail_path = "C:\wamp\bin\sendmail\sendmail.exe -t"

4.) Restart Wampserver.

You might have success using Gmail, but there are a few extra tweaks to make it work. I prefer using the mail server of the webhost where I upload my code.

 
Leave a comment

Posted by on September 10, 2010 in PHP

 

Data Validation in CakePHP

Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application. For example, you might want to make sure that passwords are at least eight characters long, or ensure that usernames are unique. Defining validation rules makes form handling much, much easier.

var $validate = array('fieldName' => 'ruleName');

<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array(
        'login' => 'alphaNumeric',
        'email' => 'email',
        'born' => 'date'
    );
}
?>

One Rule Per Field

var $validate = array(
    'fieldName1' => array(
        'rule' => 'ruleName', // or: array('ruleName', 'param1', 'param2' ...)
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // or: 'update'
        'message' => 'Your Error Message'
    )
);
  1. Single value : 'alphaNumeric'
  2. Max, min or range : array('minLength', 15)
  3. Comparison : array(‘comparision’, ‘>’,  0.00)
  4. Number : numeric
  5. Date : date
  6. Money format : array(‘decimal’, 2)
  7. Email format : email
  8. Between 0-15 characters :  array(‘between’, 0,  15)
  9. Alphabets and Number only : alphaNumeric

Multiple Rules per Field

var $validate = array(
    'fieldName' => array(
        'ruleName' => array(
            'rule' => 'ruleName',
            // extra keys like on, required, etc. go here...
        ),
        'ruleName2' => array(
            'rule' => 'ruleName2',
            // extra keys like on, required, etc. go here...
        )
    )
);


<pre>var $validate = array(
    'login' => array(
        'loginRule-1' => array(
            'rule' => 'alphaNumeric',
            'message' => 'Only alphabets and numbers allowed',
            'last' => true
         ),
        'loginRule-2' => array(
            'rule' => array('minLength', 8),
            'message' => 'Minimum length of 8 characters'
        )
    )
);

Custom Validation Rules

Custom Regular Expression Validation

<pre>var $validate = array(
    'login' => array(
        'rule' => '/^[a-z0-9]{3,}$/i',
        'message' => 'Only letters and integers, min 3 characters'
    )
);

The example above checks if the login contains only letters and integers, with a minimum of three characters.

The regular expression in the rule must be delimited by slashes. The optional trailing ‘i’ after the last slash means the reg-exp is case insensitive.

Adding your own method

Sometimes checking data with regular expression patterns is not enough. For example, if you want to ensure that a promotional code can only be used 25 times, you need to add your own validation function, as shown below:

<pre><?php
class User extends AppModel {
    var $name = 'User';

    var $validate = array(
        'promotion_code' => array(
            'rule' => array('limitDuplicates', 25),
            'message' => 'This code has been used too many times.'
        )
    );

    function limitDuplicates($check, $limit){
        //$check will have value: array('promomotion_code' => 'some-value')
        //$limit will have value: 25
        $existing_promo_count = $this->find( 'count', array('conditions' => $check, 'recursive' => -1) );
        return $existing_promo_count < $limit;
    }
}
?>
</pre>

The current field to be validated is passed into the function as first parameter as an associated array with field name as key and posted data as value.

If you want to pass extra parameters to your validation function, add elements onto the ‘rule’ array, and handle them as extra params (after the main $check param) in your function.

Your validation function can be in the model (as in the example above), or in a behavior that the model implements. This includes mapped methods.

When writing a validation rule which can be used by multiple fields, take care to extract the field value from the $check array. The $check array is passed with the form field name as its key and the field value as its value. The full record being validated is stored in $this->data member variable.

<pre><?php
class Post extends AppModel {
  var $name = 'Post';

  var $validate = array(
    'slug' => array(
      'rule' => 'alphaNumericDashUnderscore',
      'message' => 'Slug can only be letters, numbers, dash and underscore'
      )
    );

    function alphaNumericDashUnderscore($check) {
      // $data array is passed using the form field name as the key
      // have to extract the value to make the function generic
      $value = array_values($check);
      $value = $value[0];

      return preg_match('|^[0-9a-zA-Z_-]*$|', $value);
    }
}
?>
</pre>

 
Leave a comment

Posted by on June 12, 2010 in PHP

 

How to install CakePHP

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

  1. Webserver for PHP (Wamp server or Xamm)
  2. PHP 5.3.2
  3. MySQL 5
  4. CakePHP 1.3.1 : http://github.com/cakephp/cakephp/zipball/1.3.1

Installation CakePHP with Web Server

  1. Extract CakePHP file that you have download from URL above to the place and rename to “cake” only
  2. Go into this folder: cake/cake/console/ and right click on “cake.bat” file; copy this file path to past in Path of Environment Variables (System Properties -> Advanced  -> System variables)
  3. Point to PHP bin and copy it’s path to the Path of Environment Variables
  4. Point to MySQL bin and copy it’s path to the Path of Environment Variables too.
  5. Open CMD and type : cake and enter to test that cake works or not?

*Notation: Path of CakePHP, PHP, and MySQL must be separated by “;”

If you install CakePHP on Windows, it has a little bit problem that we have to fix.

Fix The Problem

  1. In cake/cake/console : copy directory “templates” to directory “libs”
  2. In cake/cake/libs/cache/file.php : change $data = unserialize((string)$data); to $data = unserialize(trim((string)$data)); in line 176

Referenced by: http://www.cakephp.org/

 
Leave a comment

Posted by on June 10, 2010 in PHP

 

Translate Language by google APIs


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title>Google AJAX Language API - Basic Translation</title>
 <script type="text/javascript" src="http://www.google.com/jsapi"></script>
 <script type="text/javascript">

 google.load("language", "1");

 function initialize() {
 google.language.translate("I love you, baby!", "en", "ko", function(result) {
 if (!result.error) {
 var container = document.getElementById("translation");
 container.innerHTML = result.translation;
 }
 });
 }
 google.setOnLoadCallback(initialize);

 </script>
 </head>

 <body>
 <div id="translation"></div>
 </body>
</html>

var google.language.Languages = {
  'AFRIKAANS' : 'af',
  'ALBANIAN' : 'sq',
  'AMHARIC' : 'am',
  'ARABIC' : 'ar',
  'ARMENIAN' : 'hy',
  'AZERBAIJANI' : 'az',
  'BASQUE' : 'eu',
  'BELARUSIAN' : 'be',
  'BENGALI' : 'bn',
  'BIHARI' : 'bh',
  'BULGARIAN' : 'bg',
  'BURMESE' : 'my',
  'CATALAN' : 'ca',
  'CHEROKEE' : 'chr',
  'CHINESE' : 'zh',
  'CHINESE_SIMPLIFIED' : 'zh-CN',
  'CHINESE_TRADITIONAL' : 'zh-TW',
  'CROATIAN' : 'hr',
  'CZECH' : 'cs',
  'DANISH' : 'da',
  'DHIVEHI' : 'dv',
  'DUTCH': 'nl',  
  'ENGLISH' : 'en',
  'ESPERANTO' : 'eo',
  'ESTONIAN' : 'et',
  'FILIPINO' : 'tl',
  'FINNISH' : 'fi',
  'FRENCH' : 'fr',
  'GALICIAN' : 'gl',
  'GEORGIAN' : 'ka',
  'GERMAN' : 'de',
  'GREEK' : 'el',
  'GUARANI' : 'gn',
  'GUJARATI' : 'gu',
  'HEBREW' : 'iw',
  'HINDI' : 'hi',
  'HUNGARIAN' : 'hu',
  'ICELANDIC' : 'is',
  'INDONESIAN' : 'id',
  'INUKTITUT' : 'iu',
  'IRISH' : 'ga',
  'ITALIAN' : 'it',
  'JAPANESE' : 'ja',
  'KANNADA' : 'kn',
  'KAZAKH' : 'kk',
  'KHMER' : 'km',
  'KOREAN' : 'ko',
  'KURDISH': 'ku',
  'KYRGYZ': 'ky',
  'LAOTHIAN': 'lo',
  'LATVIAN' : 'lv',
  'LITHUANIAN' : 'lt',
  'MACEDONIAN' : 'mk',
  'MALAY' : 'ms',
  'MALAYALAM' : 'ml',
  'MALTESE' : 'mt',
  'MARATHI' : 'mr',
  'MONGOLIAN' : 'mn',
  'NEPALI' : 'ne',
  'NORWEGIAN' : 'no',
  'ORIYA' : 'or',
  'PASHTO' : 'ps',
  'PERSIAN' : 'fa',
  'POLISH' : 'pl',
  'PORTUGUESE' : 'pt-PT',
  'PUNJABI' : 'pa',
  'ROMANIAN' : 'ro',
  'RUSSIAN' : 'ru',
  'SANSKRIT' : 'sa',
  'SERBIAN' : 'sr',
  'SINDHI' : 'sd',
  'SINHALESE' : 'si',
  'SLOVAK' : 'sk',
  'SLOVENIAN' : 'sl',
  'SPANISH' : 'es',
  'SWAHILI' : 'sw',
  'SWEDISH' : 'sv',
  'TAJIK' : 'tg',
  'TAMIL' : 'ta',
  'TAGALOG' : 'tl',
  'TELUGU' : 'te',
  'THAI' : 'th',
  'TIBETAN' : 'bo',
  'TURKISH' : 'tr',
  'UKRAINIAN' : 'uk',
  'URDU' : 'ur',
  'UZBEK' : 'uz',
  'UIGHUR' : 'ug',
  'VIETNAMESE' : 'vi',
  'WELSH' : 'cy',
  'YIDDISH' : 'yi',
  'UNKNOWN' : ''
};
 
Leave a comment

Posted by on March 4, 2010 in PHP

 

Dynamic Playlist.xml in PHP

When we want to play music in the Flash Player by dynamic playlist, we can do as below:


<?PHP
header('Content-Type: text/xml);
echo "<?xml version='1.0' encoding='UTF-8' ?>
<Playersettings autostart='yes' playall='yes' loop='yes' shuffle='no'/>
<Playlist></p>
........................";
?>

And save this file as playlist.php

.................................
flashVars-"pl1=playlist.php"
.................................

 
Leave a comment

Posted by on December 3, 2009 in ActionScript 3.0, PHP

 
 
Follow

Get every new post delivered to your Inbox.