Google Ads

Proudly Hosted on

About Me

Hi, I 'm Aditya, the guy behind this website and many other. This site acts as my web playground, where I share all about me, my work and my knowledge.

I have over 8 yrs hands on experience in PHP, Mysql, JavaScript, open sources CMS like Joomla, Wordpress etc. During these 8 years, I have worked on more than 200 projects and/or websites but could not spare time for my blog.

 

 

Archive for the ‘PHP’ Category


Today i want to share a very simple and easy to use Paypal class. If you are a web developer you must have integrated Paypal on your websites. With the help of this class you can handle paypal payment as well as instant payment notification. Frankly speaking i have not created the class but have used it so many times with great success. Thanks to the original developer.

It includes two php files, one is the class and other one is the implementation.

SocialTwist Tell-a-Friend More
Tags: , , ,   |  Posted under Payment Gateway, PHP  |  Comments  Comments Off on PayPal class
Last Updated on Sunday, 4 July 2010 05:34

PHP5 and XML

While PHP has offered XML support since its early versions, that support improved exponentially with the introduction of PHP5. Because the PHP4 support for XML was somewhat limited, such as offering only a SAX-based parser enabled by default and the PHP4 DOM not implementing the W3C standard, PHP XML developers reinvented the wheel, so to speak, with PHP5 and complied with commonly used standards.

New for XML in PHP5

PHP5 includes totally rewritten and new extensions, including the SAX parser, the DOM, SimpleXML, XMLReader, XMLWriter, and the XSLT processor. All these extensions are now based on the libxml2.

Along with the SAX support improved from PHP4, PHP5 also supports both the DOM according to W3C standard and the SimpleXML extension. SAX, DOM, and SimpleXML are all enabled by default. If you are familiar with the DOM from other languages, you will have an easier time coding with similar functionality in PHP than before.

 

Reading, manipulating, and writing XML in PHP5

SimpleXML, in combination where necessary with the DOM, is the ideal choice for developers working with straightforward, predictable, and relatively small XML documents to read, manipulate, and write XML in PHP5.

Of the many APIs available in PHP5, the DOM and SimpleXML are the most familiar, in the case of the DOM, and the easiest to code, in the case of SimpleXML.And for the most common situations, like those you are dealing with here, the most functional.

DOM extension

The Document Object Model (DOM) is a W3C standard set of objects for representing HTML and XML documents, a standard model of how you can combine these objects, and a standard interface for accessing and manipulating them. Many vendors support the DOM as an interface to their proprietary data structures and APIs, which gives the DOM model a lot of authority with developers due to its familiarity. The DOM is easy to understand and utilize since its structure in memory resembles the original XML document. To pass on information to the application, DOM creates a tree of objects that duplicates exactly the tree of elements from the XML file, with every XML element being a node in the tree. The DOM is a tree-based parser. Because DOM builds a tree of the entire document, it uses a lot of memory and processor time. Therefore, performance issues make it impractical to parse large documents with DOM. The key use of the DOM extension in the context of this article is its ability to import SimpleXML format and output DOM format XML, or the reverse, for use as a string or XML file.

SimpleXML

The SimpleXML extension is the tool of choice for parsing an XML document. The SimpleXML extension requires PHP5 and includes interoperability with the DOM for writing XML files and built-in XPath support. SimpleXML works best with uncomplicated, record-like data, such as XML passed as a document or string from another internal part of the same application. Provided that the XML document isn't too complicated, too deep, and lacks mixed content, SimpleXML is easier to code than the DOM, as its name implies. It is also more reliable if you work with a known document structure.

 

The DOM in action

The DOM is the W3C DOM specification that you work with in a browser and manipulate with JavaScript. It has all the same methods, so you will use familiar coding techniques. Listing 2 illustrates the use of the DOM to create an XML string and XML document, formatted for your viewing pleasure.

Listing 2. Using the DOM

  <?php      //Creates XML string and XML document using the DOM    $dom = new DomDocument('1.0');      //add root - <books>    $books = $dom->appendChild($dom->createElement('books'));      //add <book> element to <books>    $book = $books->appendChild($dom->createElement('book'));      //add <title> element to <book>    $title = $book->appendChild($dom->createElement('title'));      //add <title> text node element to <title>    $title->appendChild(                    $dom->createTextNode('Great American Novel'));      //generate xml    $dom->formatOutput = true; // set the formatOutput attribute of                               // domDocument to true    // save XML as string or file    $test1 = $dom->saveXML(); // put string in test1    $dom->save('test1.xml'); // save as file    ?>  

 

This produces the output file in Listing 3.

Listing 3. The output file

    <?xml version="1.0"?>   <books>     <book>       <title>Great American Novel</title>     </book>   </books>  

 

Listing 4 imports a SimpleXMLElement object into a DOMElement object, illustrating the interoperability of the DOM and SimpleXML.

Listing 4. Interoperability, Part 1 — DOM imports SimpleXML

   <?php      $sxe = simplexml_load_string('<books><book><title>'.         'Great American Novel</title></book></books>');      if ($sxe === false) {     echo 'Error while parsing the document';     exit;   }      $dom_sxe = dom_import_simplexml($sxe);   if (!$dom_sxe) {     echo 'Error while converting XML';     exit;   }      $dom = new DOMDocument('1.0');   $dom_sxe = $dom->importNode($dom_sxe, true);   $dom_sxe = $dom->appendChild($dom_sxe);      echo $dom->save('test2.xml');      ?>  

 

The function in Listing 5 takes a node of a DOM document and makes it into a SimpleXML node. You can then use this new object as a native SimpleXML element. If any errors occur, it returns FALSE.

Listing 5. Interoperability, Part 2 — SimpleXML imports DOM

   <?php   $dom = new domDocument;   $dom->loadXML('<books><book><title>Great American   Novel</title></book></books>');   if (!$dom) {      echo 'Error while parsing the document';      exit;   }      $s = simplexml_import_dom($dom);      echo $s->book[0]->title; // Great American Novel   ?>  

 

 

>

SimpleXML in action

The SimpleXML extension is the tool of choice for parsing an XML document. The SimpleXML extension includes interoperability with the DOM for writing XML files and built-in XPath support. SimpleXML is easier to code than the DOM, as its name implies.

For those of you who might be new to PHP, Listing 6 formats a test XML file as an include for your convenience.

Listing 6. Test XML file formatted as a PHP include called example.php in the following code samples

  <?php     $xmlstr = <<<XML     <books>     <book>      <title>Great American Novel</title>      <characters>       <character>        <name>Cliff</name>        <desc>really great guy</desc>       </character>       <character>        <name>Lovely Woman</name>        <desc>matchless beauty</desc>       </character>       <character>        <name>Loyal Dog</name>        <desc>sleepy</desc>       </character>      </characters>      <plot>       Cliff meets Lovely Woman.  Loyal Dog sleeps, but wakes up to bark       at mailman.      </plot>      <success type="bestseller">4</success>      <success type="bookclubs">9</success>     </book>     </books>   XML;    ?>  

 

In an Ajax application, you might want to extract the zip code from an XML document and query a database. Listing 7 extracts <plot> from your example XML include directly above.

Listing 7. Extracting the Node — How easy does it get?

      <?php       include 'example.php';       $xml = new SimpleXMLElement($xmlstr);       echo $xml->book[0]->plot; // "Cliff meets Lovely Woman. ..."     ?>   

 

On the other hand, you might want to extract a multi-line address. When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply. Listing 8 demonstrates this functionality.

Listing 8. Extracting multiple instances of an element

   <?php      include 'example.php';        $xml = new SimpleXMLElement($xmlstr);        /* For each <book> node, echo a separate <plot>. */    foreach ($xml->book as $book) {      echo $book->plot, '<br />';    }        ?>  

 

In addition to reading element names and their values, SimpleXML can also access element attributes. In Listing 9, access attributes of an element just as you would elements of an array.

Listing 9. Demonstrating SimpleXML accessing the attributes of an element

    <?php      //Input XML file repeated for your convenience        $xmlstr = <<<XML    <?xml version='1.0' standalone='yes'?>      <books>     <book>      <title>Great American Novel</title>      <characters>       <character>        <name>Cliff</name>        <desc>really great guy</desc>       </character>       <character>        <name>Lovely Woman</name>        <desc>matchless beauty</desc>       </character>       <character>        <name>Loyal Dog</name>        <desc>sleepy</desc>       </character>      </characters>      <plot>       Cliff meets Lovely Woman.  Loyal Dog sleeps, but wakes up to bark       at mailman.      </plot>      <success type="bestseller">4</success>      <success type="bookclubs">9</success>     </book>    </books>  XML;    ?>      <?php    include 'example.php';        $xml = new SimpleXMLElement($xmlstr);        /* Access the <success> nodes of the first book.    * Output the success indications, too. */    foreach ($xml->book[0]->success as $success) {       switch((string) $success['type']) {            // Get attributes as element indices       case 'bestseller':           echo $success, ' months on bestseller list';           break;       case 'bookclubs':           echo $success, ' bookclub listings';           break;       }    }    ?>  

 

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, by default, PHP treats the element as an object, as Listing 10 demonstrates.

Listing 10. Call it a string or lose

    <?php           include 'example.php';        $xml = new SimpleXMLElement($xmlstr);        if ((string) $xml->book->title == 'Great American Novel') {       print 'My favorite book.';    }        htmlentities((string) $xml->book->title);    ?>   

 

Data in SimpleXML doesn't have to be constant. Listing 11 will output a new XML document, shown below, just like the original, except that the new XML will change Cliff to Big Cliff.

Listing 11. Changing text node using SimpleXML

  <?php     $xmlstr = <<<XML     <?xml version='1.0' standalone='yes'?>     <books>      <book>       <title>Great American Novel</title>       <characters>        <character>         <name>Cliff</name>         <desc>really great guy</desc>        </character>        <character>         <name>Lovely Woman</name>         <desc>matchless beauty</desc>        </character>        <character>         <name>Loyal Dog</name>         <desc>sleepy</desc>        </character>       </characters>       <plot>        Cliff meets Lovely Woman.  Loyal Dog sleeps, but wakes up to bark        at mailman.       </plot>       <success type="bestseller">4</success>       <success type="bookclubs">9</success>      </book>     </books>   XML;      ?>       <?php       include 'example.php';     $xml = new SimpleXMLElement($xmlstr);       $xml->book[0]->characters->character[0]->name = 'Big Cliff';       echo $xml->asXML();     ?>   

 

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes. Listing 12 will output an XML document based on the original but having a new character and descriptor.

Listing 12. Adding children and text nodes using SimpleXML

  <?php     $xmlstr = <<<XML     <?xml version='1.0' standalone='yes'?>     <books>      <book>       <title>Great American Novel</title>       <characters>        <character>         <name>Cliff</name>         <desc>really great guy</desc>        </character>        <character>         <name>Lovely Woman</name>         <desc>matchless beauty</desc>        </character>        <character>         <name>Loyal Dog</name>         <desc>sleepy</desc>        </character>        <character>         <name>Yellow Cat</name>         <desc>aloof</desc>        </character>       </characters>       <plot>        Cliff meets Lovely Woman.  Loyal Dog sleeps, but wakes up to bark        at mailman.       </plot>       <success type="bestseller">4</success>       <success type="bookclubs">9</success>      </book>     </books>   XML;         ?>       <?php     include 'example.php';     $xml = new SimpleXMLElement($xmlstr);       $character = $xml->book[0]->characters->addChild('character');     $character->addChild('name', 'Yellow Cat');     $character->addChild('desc', 'aloof');       $success = $xml->book[0]->addChild('success', '2');     $success->addAttribute('type', 'reprints');       echo $xml->asXML();     ?>   

 

SocialTwist Tell-a-Friend More
Posted under PHP, XML  |  Comments  Comments Off on XML and PHP
Last Updated on Sunday, 7 February 2010 05:24

PHP is one of the most widely used open-source server-side scripting languages that exist today. With over 20 million indexed domains using PHP, including major websites like Facebook, Digg and WordPress, there are good reasons why many Web developers prefer it to other server-side scripting languages, such as Python and Ruby.

Some of the most powerful PHP classes and libraries are as follows:

 

Databases

  • ADOdb
    Object-oriented library. Made by pobraztsu Microsoft ADO, but has several enhancements that make it unique (for example, summary tables, caching records …) Supports many databases including: MySQL, PostgreSQL, Interbase, Firebird, Informix, Oracle, MS SQL, FoxPro , Access, ADO, Sybase, FrontBase, DB2, SAP DB, SQLite, Netezza, LDAP.
  • Doctrine
    Represents an object-relational mapping (ORM) in PHP 5.2.3 +. A key feature of this library is that it allows you to write database queries in object-oriented form, with its own dialect of SQL – Doctrine Query Language (DQL). This is a powerful alternative to conventional SQL-queries.
  • PHPLINQ
    A set of PHP-Classes for database management.

Working with documents

Allows you to create ZIP-archives (WinZip, PKZIP). PclZip determines the object class

  • TCPDF
    Class that generates PDF documents. Does not require other libraries, supported formats ISO, including UTF-8, Unicode, RTL, and HTML.
  • PHPPowerPoint
    Open standards-based Microsoft OpenXML. Allows you to read and write documents PowerPoint. Gives the ability to manage meta-data (author, title, description, …), add the slides and images in presentations and much more.
  • PHPExcel
    Also works on Microsoft OpenXML. Allows you to read and save files in Excel. Features include: editing meta data (author, title, description, …), managing spreadsheets, fonts, styles, add images, and much more.
  • PhpRtf Lite
    Allows you to create and edit compatible with MS Word and Open Office Writer, RTF with PHP. Allows you to control almost everything. Compatible with UTF-8.
  • PclZip

Email

  • Swift Mailer
    Swift Mailer is easily integrated into any PHP-application. It is a flexible and elegant OOP approach to sending messages with multiple functions: sending email using SMTP, SendMail, Postfix, support for servers, etc.
  • PHPMailer
    Best class for working with e-mail. mail. Supports message in digital form, S / MIME encryption, text and HTML-mail, images, supports several Email'ov, SMTP-authentication.

Forms

  • Securimage PHP Captcha
    Script for creating complex images (captures) for protection against spammers. Easily added to any shape.
  • phpObjectForms
    OOP library for creating and processing HTML-forms. Key Features: Supports all standard forms of input, checking on the server side using regular expressions, checking on the client side using Javascript, supports a form template. Styles forms are written in CSS and you can easily customize their display.

Images / media / files

Asido offers the following functions: image resizing, applying watermarks to images, rotate, copy, image cropping, conversion to grayscale, and more.

  • Asido
  • PHP Thumb
    A small library for working with images: resizing, rotation, Crop. You can also add custom features. It can perform multiple actions in succession, without neodhodimosti save and re-initialize the class with all the manipulations.
  • WideImage
    OOP library for working with images. It provides a simple way of loading and storing images from files, databases, and URL. Supports most popular image formats: GIF, PNG, JPEG, GD and GD2.
  • Smart Image Resizer
    Allows you to resize and kropat any images on your site actually they are not touching. Simply upload the image to its maximum size and then use any part of it. It has many useful functions.
  • class.upload.php
    It's a little PHP-script to download images and management on the server. It can convert images from one format to another, resize, add labels, watermarks, and "wash out" the image. You can use it for files that are downloaded with the aid of HTML-forms, Flash Uploader or local files.
  • getID3 ()
    PHP-script that extracts useful information from MP3 and other multimedia formats (OGG, WMA, WMV, ASF, WAV, AVI, AAC, VQF, FLAC, MusePack, Real, QuickTime, Monkey's Audio, MIDI, etc.)

Javascript / AJAX

  • PHPLiveX
    A small library that allows you to easily integrate AJAX technology into your web project. You can send the form data and send the request to another page without reloading the current one.
  • Xajax
    Very famous library and Javascript-engine that allows you to easily create powerful Ajax-applications using HTML, CSS, Javascript, PHP. Pages have the opportunity to send asynchronous requests to the server and update page content without it rebooting.

RSS / Atom

  • SimplePie
    PHP-class, which provides a simple API to perform all the dirty work of receiving, caching, parsing, and normalization of the structure of RSS and Atom formats.

Safety

Testing and debugging

Webservices

SocialTwist Tell-a-Friend More
Tags: ,   |  Posted under PHP  |  Comments  Comments Off on Useful PHP classes and libraries
Last Updated on Saturday, 16 January 2010 05:01

 Shorthand for asynchronous JavaScript and XML, is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page.

The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of JavaScript and XML is not actually required, nor do the requests need to be asynchronous.

AJAX is based on the following web standards:

  • JavaScript
  • XML
  • HTML
  • CSS

AJAX uses the XMLHttpRequest object

To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.

With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server – without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

To demonstrate the AJAX PHP connection we will create a very simple form with 2 input fields. In the first field you can type any text and we will send this text to our PHP script which will convert it to uppercase and sends it back to us

HTML code

<body>
	<form name="testForm">

	Input text: <input type="text" onkeyup="doWork();" 
	name="inputText" id="inputText" />

	Output text: <input type="text" name="outputText" 
	id="outputText" />

	</form>

</body>

1. First step

 // Get the HTTP Object 
 function getHTTPObject(){ 
 
	if (window.ActiveXObject) 

 		return new ActiveXObject("Microsoft.XMLHTTP"); 
  	else if (window.XMLHttpRequest) 
 
		return new XMLHttpRequest(); 
 
	else { 
 
		alert("Your browser does not support AJAX."); 
		return null; 
		} 
	}

2. Second Step

// Implement business logic 
 function doWork(){ 
 	 httpObject = getHTTPObject(); 
	 if (httpObject != null) {  
	 	httpObject.open("GET", "upperCase.php?
		inputText="+document.getElementById
		('inputText').value, true); 
		httpObject.send(null); 
		httpObject.onreadystatechange = setOutput; 
		} 
	 }

3. The last step on client side is to implement the setOutput() function which will change the value of our second field.

  • 0 = uninitialized
  • 1 = loading
  • 2 = loaded
  • 3 = interactive
  • 4 = complete
// Change the value of the outputText field 
 function setOutput(){ 
 	 if(httpObject.readyState == 4){ 
	 	document.getElementById('outputText').value 
		= httpObject.responseText; 
		} 
	 } 

 

Implementing the server side functionality is very simple compared to the client side. In the PHP code we just need to check the $_GET super-global array. Afterwards convert it to uppercase and echo the result. So the PHP code is this:

<?php if (isset($_GET['inputText']))
      	echo strtoupper($_GET['inputText']);
      ?>
SocialTwist Tell-a-Friend More
Tags: , ,   |  Posted under Ajax, PHP, Technology  |  Comments  Comments Off on AJAX
Last Updated on Saturday, 15 May 2010 11:54

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.

Features

 

  • No Configuration – Set-up the database and let the magic begin
  • Extremely Simple – Just look at the name…It's Cake
  • Active, Friendly Community – Join us #cakephp on IRC. We'd love to help you get started
  • Flexible License – Distributed under the MIT License
  • Clean IP – Every line of code was written by the CakePHP development team
  • Best Practices – covering security, authentication, and session handling, among the many other features
  • OO – Whether you are a seasoned object-oriented programmer or a beginner, you'll feel comfortable     
SocialTwist Tell-a-Friend More
Tags: ,   |  Posted under MVC, PHP  |  Comments  Comments Off on Cake Php
Last Updated on Sunday, 13 December 2009 09:49