PHP cURL – Exposing data to a Node application
In this post we will explore how to expose PHP data to a Node application. We will build a simple hello world app to demonstrate this and then build a chat application where we can expose chat history from a database to users as well as keep users updated in the change in user details.
Now, it is fair to say we could do all of this in Node and have done with it but there are many situations where you will be building apps in PHP and need to expose that data in real time. You will also come across situations where data is handled in PHP but needs to be processed on a different URL using a different protocol – a Node app hosted on an Express server package would be an ideal example of that!
We will:
- Examine how CURL works
- Demonstrate it using a Hello World app using Node
- Explore some advanced concepts of how to process data using CURL and Node
- Reinforce our learning by building a chat application using the skills we have acquired above
What is cURL?
cURL is a module that can expose server side data to a client facing script or to another server. This is particularly helpful when you are having to communicate or expose data to different environments using a different language other than PHP.
The great advantage with cURL is that the data can be bundled up in any format you like such as XML, JSON or CSV – this makes it incredibly flexible. As long as you know what the receiving server is expecting the data in you are good to go! You can also adapt it to be used with FTP servers to enable users to upload data on the fly such as video or audio files.
For our examples we will be using JSON.
Let’s take a look at a very simple example:
cURL Hello World App
Our folder structure will be:
chat_app php index.php index.js package.js node_modules
We’ll start by examining the PHP (php/index.php)
'ExampleUsername', 'accountType' => 'Administrator' ); //Encode the array ($userDetails) into JSON. $jsonDataEncoded = json_encode($userDetails); //Tell cURL that we want to send a POST request. 1 meaning true curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json // There is an option to set this on thee node end using body-parser module of node Express server curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //Execute the request $result = curl_exec($ch);
What’s happening?
We start by defining a URL – we are listening on port 3000 -it can be any port number you want. We then initialize a cURL object and attach it to a variable called $ch.
The next step is to create a data source – this would normally be generated by a database call but for this example we will create a simple associative array. We then encode this as JSON. The next step is to tell cURL how we want the data sent – GET or POST. For this example we will use POST.
A quick note on GET and POST. The same considerations apply to when using GET or POST in a normal PHP setting. For example use GET for small amounts of non-sensitive data and POST for sensitive info or large amounts of data.
So that’s the PHP side bit done – let’s take a look at the Node server (index.js).
var express = require('express'); //Load in body-parser package var bodyParser = require('body-parser'); var json = require('json') var app = express(); //assign bodyParser object to app and parse JSON app.use(bodyParser.json()) var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('CURL App 1 listening at http://%s:%s', host, port); }); app.post('/users', function (req, res) { var data = req.body; res.send('Got a POST request: ' + data.username); });
What’s happening?
We begin defining our environment variables which includes the Express server, the JSON and body-parser modules as well as an Express object by attaching a variable app.
The next step, though not required but great for sys admin purposes is to output to the console the port our Express server is listening on. The next step we create an event listener for our post URL. We use two arguments (request and response). We request our JSON encoded data and respond by outputting that we have a post request with a variable we created in our PHP array.
What have we explored so far?
We have learnt what cURL is and why it can help us. We then explored a very basic example of how to expose data between two servers using two different architectures (PHP and Node).
What next?
Our next objective is to scale this example up into something a bit more meaty. In our next example we will use Codeigniter for our PHP framework and use Socket.io in conjunction with Express Node server to really unleash the power of dynamic realtime updates.
We will also learn about some key aspects of cURL that will help keep your code clean and prevent wasted resources.