0

Is there a way to send any kind of request from the PHP script to the Node.js script?

For example I have this directory:

scripts
|_sender.php
|_receiver.js

I want to send some data from php script and read it with node.js script to execute some action.

How is this done properly?

6
  • You can send a request with PHP (cURL or Guzzle) or you can setup a message queue or you could poll the DB. Lots of options but what is your use case? Why this node layer? Commented Aug 24, 2016 at 11:44
  • @nerdlyist Because our app is written in CakePHP and our Google API is written in Node.js. Commented Aug 24, 2016 at 11:45
  • So your node portion is a restful api? Then I would go for making a request to that with Guzzle. What is that receiver.js doing? Commented Aug 24, 2016 at 11:48
  • This is just example of their positions. I would usually run node.js script from php like this: <?php exec('node receiver.js') Commented Aug 24, 2016 at 11:50
  • Okay but what is receiver.js doing. Is it making the request to the node api? Commented Aug 24, 2016 at 11:59

2 Answers 2

4

The easiest way I use is to pass your PHP data to node using HTTP post or get, here is my code to send data from PHP to the node.

// Node Side
var express = require('express');
express = express();
var bodyParser = require('body-parser');
express.use(bodyParser.json());

express.post('/get_php_data', function (req, res) {
    // php array will be here in this variable
    var data = req.body.data;
    
    
    res.send(' Done ');
});

// PHP Side
httpPost('NODE_URL:2200/get_php_data', array('data' => 'some data'));

function httpPost($url,$params)
{
    $postData = http_build_query($params);
    $ch = curl_init();  
 
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_POST, count($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    

    $output=curl_exec($ch);

    curl_close($ch);
    return $output;
} 
Sign up to request clarification or add additional context in comments.

Comments

1

It depends where js will read it incoming data

If it is a server, start it with node receiver.js then send from your php to http://local host/.... Whatever your server is listening on

Or you can dump your php output into a file and read it by the receiver after

You should provide more informations to get a better answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.