tags:

views:

190

answers:

2

I'm currently working on a small application that works like this:

  • When the user clicks a link, an Ajax GET request is fired.
  • The request hits a server-side PHP script.
  • The script, which requests information for another domain, retrieves a JSON feed.
  • The feed is then echoed back to the client for parsing.

I'm not really a PHP developer, so I am looking for some best practices with respect to cross-domain requests. I'm currently using file_get_contents() to retrieve the JSON feed and, although it's functional, it seems like a weak solution.

+3  A: 

Does the PHP script do anything other than simply call the other server? Do you have control over what the other server returns? If the answers are No and Yes, you could look into JSONP.

Paolo Bergantino
+1  A: 

You might want to abstract the retrieval process in PHP with an interface so you can swap out implementations if you need too. Here is a naive example:

interface CrossSiteLoader 
{
    public function loadURL($url);
}

class SimpleLoader implements CrossSiteLoader
{
    public function loadURL($url)
    {
        return file_get_contents($url);
    }
}

Comes in handy if you need to test locally with your own data because you can use a test implementation:

public ArrayLoader implements CrossSiteLoader
{
    public function loadURL($url)
    {
        return json_encode(array('var1' => 'value1', 'var2' => 'value2'));
    }
}

or if you just want to change from file_get_contents to something like curl

rojoca