0

Im designing a php API, I give to my user a php file (core.php) to add on their servers. And then to use it they just have to include_once('api/core.php'). Inside core.php I need to create some functions that just parse json files from my main server.

Lets say they need a complete user list, so they will have to do something like:

include_once('api/core.php');
print_r(myApi_list('user','all'));

Inside core.php the function will be something like:

function myApi_list($pa, $pb) {
  if($pa == 'user') {
    //here will be a code that call my server
    return resp;
  } 
  //more stuf
}

And of course there will be another script on my server that will handle the sql querys and security stuff. My problem is, what will be the best way to call my server from core.php, should I use file_get_contents? and just tell my server script to answer with maybe a json file (and then core.php just parse that)? Or should I user cUrl? Since this is an API i will prefer to use the module that is more likely to be active by default on a php sever.

What do you think is the best approach on this situation?

DomingoSL
  • 14,920
  • 24
  • 99
  • 173

2 Answers2

2

My recommondation is cURL.

The function file_get_contents is very limited in its use itself. It can only return the data or false.

cURL on the otherhand has many options. So you can make clean errors messages what went wrong, 404 api is out of business, 500 server down etc. Also cURL has the options to use POST values, file_get_contents not.

Also file_get_contents has the limitation of allow_url_foppen (which can disable the function to be used for external adresses), see this question (which also suggests using cURL over file get contents

Community
  • 1
  • 1
MKroeders
  • 7,562
  • 4
  • 24
  • 39
  • 1
    I would go with curl over file_get_contents() and then you can post data directly to your server and use stuff like SSL etc properly. + you get better error reporting – Dave Apr 29 '13 at 13:40
1

If it is just JSON what you get back, use file_get_contents(). It's alot easier and takes less time coding. Simply set the header of the script on the main server to header('Content-type: text/json');, then use file_get_contents() and parse that response.

If the response is empty, there's an invalid api-request (or just no data for that query, could be caught by returning "No data found"). If the parse of the response is null, there's an error on the server.

Richard de Wit
  • 7,102
  • 7
  • 44
  • 54