Mar
06

Cross-Domain AJAX calls using PHP

AJAX has become the core component of many web applications around us. And its fairly easy to handle AJAX now a days, with the help of various javascript libraries (ex: jQuery, Prototype, Mootools, YUI, etc). But there is one security issue that web browsers impose in doing AJAX calls - they don’t let you do AJAX calls in web servers different than yours. That means, if your script is in www.mydomain.com and you’re trying to do AJAX call to www.anotherdomain.com/get.php, then the browser will through error like: “Error: uncaught exception: Permission denied to call method XMLHttpRequest.open”.

Now, there are a number of solutions to this problem. Instead of explaining them all to you, lemme provide you the simplest one: using a PHP transport file. If you already know the thing and just need the script, download from here.

Others, let’s see an example implementation first.

Example use

   1: xmlHttp.onreadystatechange=function()
   2: {
   3:     if(xmlHttp.readyState==4)
   4:     {
   5:         alert(xmlHttp.responseText);
   6:     }
   7: }
   8:  
   9: xmlHttp.open(“GET”, ‘http://myserver.com/transport.php?action=’ + 
  10:                     urlencode(‘different-server.com/return_call.php’) +
  11:                     ‘&method=get&data1=101&data2=pass’, true );
  12:  
  13: xmlHttp.send(null);

Now, lets see how it works:

  1. The script makes an AJAX call to the myserver.com/transport.php with a few parameters:
    • action = the target URL you need to fetch, from a different domain
    • method = the HTTP method (post/get)
    • data1, data2 = sample parameters for using as either query-string or POST fields
  2. When the request is received by transport.php, it uses cURL to make a call to the page mentioned in action.
  3. Based on the method, it either makes a GET request or a POST request. In both cases, it sends the extra parameters that are sent.
  4. After the response is received, transport.php echoes it. So, you have what you need!

Download

transport.php
Cross-Domain AJAX call transporter.
Downloaded: 806 times

Comments and suggestions are most welcomed :)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Furl
  • Ma.gnolia
  • Technorati
  • YahooMyWeb
  • BlinkList
  • NewsVine
  • Reddit
  • Simpy
  • Spurl
Jan
20

HTTP Class for PHP (supports both cURL and fsockopen)

This is a wrapper HTTP class that uses either cURL or fsockopen to harvest resources from the web. It supports a handy subset of functionalists of HTTP that are mostly needed in day to day coding. Scripts who need to communicate with other servers will find it useful. If you’re looking to invoke any RESTful API and don’t want to bother adding a bunch of libraries for that simple thing, just put this class and you’re set.

Detailed documentation can be found here. And you can download the source from here.

UPDATE: Class added in Orchid - “PHP framwork for the rest of us”

Features

  • Can use both cURL and fsockopen.
  • Degrades to fsockopen if cURL not enabled.
  • Supports HTTP Basic authentication.
  • Supports defining custom request headers.
  • Supports defining connection timeout values.
  • Supports defining user agent and referral values.
  • Supports both user-defined and persistent cookies.
  • Supports secure connections (HTTPS) with and without cURL.
  • Supports adding requests parameters for both GET and POST.
  • Supports automatic redirection (maximum redirect can be defined).
  • Returns HTTP response headers and response body data separately.

Example 1 - Simple Get (Facebook Application List)

   1: <?php
   2:  
   3: include_once(‘class.http.php’);
   4:  
   5: $http = new Http();
   6:  
   7: $http->execute(‘http://www.facebook.com/apps/index.php?sort=6′);
   8: echo ($http->error) ? $http->error : $http->result;
   9:  
  10: ?>

Example 2 - Invoking Yahoo Term Extraction API

   1: <?php
   2:  
   3: include_once(‘class.http.php’);
   4:  
   5: $http = new Http();
   6:  
   7: $http->addParam(‘appid’   , ‘a_really_random_yahoo_app_id’);
   8: $http->addParam(‘context’ , ‘I am happy because I bought a new car’);
   9: $http->addParam(‘output’  , ‘xml’);
  10:                         
  11: $http->execute(‘http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction’);
  12: echo ($http->error) ? $http->error : $http->result;
  13:  
  14: ?>

Example 3 - Logging into Basecamp (without using cURL!)

   1: <?php
   2:  
   3: include_once(‘class.http.php’);
   4:  
   5: $http = new Http();
   6:  
   7: $http->useCurl(false);
   8: $http->setMethod(‘POST’);
   9:  
  10: $http->addParam(‘user_name’, ‘emran’);
  11: $http->addParam(‘password’, ‘hasan’);
  12:  
  13: $http->setReferrer(‘https://someproject.projectpath.com/login’);
  14: $http->execute(‘https://someproject.projectpath.com/login/authenticate’);
  15:  
  16: echo ($http->error) ? $http->error : $http->result;
  17:  
  18: ?>

Example 4 - Getting a protected feed

   1: <?php
   2:  
   3: include_once(‘class.http.php’);
   4:  
   5: $http = new Http();
   6: $http->setAuth(‘emran’, ‘hasan’);
   7:  
   8: $http->execute(‘http://www.someblog.com/protected/feed.xml’);
   9: echo ($http->error) ? $http->error : $http->result;
  10:  
  11: ?>

Download

class.http.php
HTTP Class for PHP (supports both cURL and fsockopen)
Downloaded: 983 times
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Furl
  • Ma.gnolia
  • Technorati
  • YahooMyWeb
  • BlinkList
  • NewsVine
  • Reddit
  • Simpy
  • Spurl
Jul
23

Htpasswd protection library for Code Igniter

This is a library designed to run with Code Igniter that allows the application to protect any folder in the webserver using the htpasswd method of Apache. It can also group the users and create group based permission on the folders. The use is very simple: you need to define an array of the users (and array of groups if you need that), tell it where to store the password files and tell which folder to protect. It will do the rest for you. Here goes the function:

    /**
     * Protect a given folder with htpasswd protection method
     *
     * @author  Md Emran Hasan <emran@rightbrainsolution.com>
     * @param   string  location of the folder to protect
     * @param   string  location of the folder to write the group and password file
     * @param   array   an array with the users info (username and password)
     * @param   array   an array with the groups along with their user list
     * @return  boolean
     * @access  public
     */
    function protect($protectFolder, $passFolder, $userData, $groupData = array())

It is a small part of the large protection library I have been developing for a membership management application called MemberSmart . This application allows someone to protect their PHP and non-PHP based files residing in a server in a number of ways. Among the methods, the htpasswd is the most easy and convenient one. This application will be released soon by the client I am working for.

Download the library with the example from htpasswd.zip. Here is an example controller highlighting the use of the library.

<?php

class Protect extends Controller {

    function Protect()
    {
        parent::Controller();
    }
    
    function index()
    {
        // Load the library
        $this->load->library(‘AuthHtpasswd’);
        
        // Create the user array (this might come from your db)
        $userData = array(
                            array(
                                    ‘username’ => ‘admin’,
                                    ‘password’ => ‘root’
                                 ),
                            array(
                                    ‘username’ => ‘test’,
                                    ‘password’ => ‘test123′
                                 ),
                            array(
                                    ‘username’ => ‘emran’,
                                    ‘password’ => ‘hasan’
                                 )
                         );

        // Create the group array (this might also come from your db)
        $groupData = array(
                            array(
                                    ‘name’ => ‘ADMIN’,
                                    ‘users’ => array(‘admin’, ‘emran’)
                                 ),
                            array(
                                    ‘name’ => ‘QA’,
                                    ‘users’ => array(‘test’)
                                 )
                         );

        // Define the root to the folders
        $rootDir = $_SERVER[‘DOCUMENT_ROOT’] . DIRECTORY_SEPARATOR;

        // Protect them!
        $action = $this->authhtpasswd->protect($rootDir . ‘cs’,
                                         $rootDir . ‘data’,
                                         $userData,
                                         $groupData
                                        );

        // Is there any error? If yes, then show them!
        if (!$action)
        {
            $this->authhtpasswd->printErrors();
        }
    }
}
?>

Md Emran Hasan
Co-founder & CTO
Right Brain Solution Ltd.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Furl
  • Ma.gnolia
  • Technorati
  • YahooMyWeb
  • BlinkList
  • NewsVine
  • Reddit
  • Simpy
  • Spurl
Jun
09

Code Igniter Rocks !

Code Igniter

A few days back I discovered CakePHP and was very impressed with it. I started to code one of my apps with it but my impression decreased when i wanted to deploy it. After several methods and even communicating in their IRC, I wasnt able to deploy the app - total wastage of my time !!!

My search for a framework thats as easy (or easier ?) as Cake but having smooth deploy feature started again. I heard about Code Igniter before, but didnt give it much attention. Now I decided to visit their site. The one thing that forced me to give attention to it this time was this text on their site:

“If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks that require rocket science to understand, Code Igniter might just be the right tool for you.”

I decided to test it out and to my surprise, they are not lying a bit ! I was able to create a site for one client in super-cool way in a lot lesser time than it would actually take without it. While coding the app, I loved CI’s simplicity, its non-geeky style framework functions and their simple usages, the top-notch documentation and a good user base for knowledge searching.

Now I know which framework I should use for my projects. Certainly Cake is more robust framework than CI, but CI beats it by its simplicity. And I also love that !

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Furl
  • Ma.gnolia
  • Technorati
  • YahooMyWeb
  • BlinkList
  • NewsVine
  • Reddit
  • Simpy
  • Spurl
May
03

Cake 1.0 released !

Cake PHPI can’t start my day without Coffee. I can’t live my day without Cake ! And now they have a stable Cake !!!

Yes, the long-awaited Cake PHP 1.0 is out ! Not only its the first official stable release, but also its boosted with lots of bugfixes and all the great cake features. Also, the website of Cake PHP is revamped with the new design - looks simple yet appealing. Thanks to Armando Sosa for his contribution.

People, if you havent already tasted Cake, its the best time to start so ! Don’t miss the yummy bites !! Go get it !!!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Furl
  • Ma.gnolia
  • Technorati
  • YahooMyWeb
  • BlinkList
  • NewsVine
  • Reddit
  • Simpy
  • Spurl
top