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?
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;
}
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
Related
I've took some code from other posts to implement Apache app to request Node app.
Following Node app "works" but I cannot access post parameters which are undefined.
//NODE
express = require('express');
bodyParser = require('body-parser');
app = express();
port = 3000;
app.use(bodyParser.json());
app.post('/get_php_data', function (req, res) {
// php array will be here in this variable
var data = req.param.data; // I've tried req.body.data;
var response = String(data)+String((7*data+3*data+1*data) % 3);
console.log(req); // This seems log req parameter in a loop
res.send(data);
});
app.listen(port);
PHP-part (just POST request with one parameter):
echo httpPost('localhost:3000/get_php_data', array('data' => 1));
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;
}
This setup returns undefined. How to access POST parameters with Node?
Well, answer was simple. In Node script change the 5th line as follows:
//app.use(bodyParser.json());
app.use(bodyParser());
You don't have to run server if they are on same machine you can use php `` which interprets commands line. No need to run http on same machine to reach it.
Hello I am trying to connect from my site with curl (php) to a rest api (node js-express-js) i have made. Everythink seems to work fine except the answer from curl is empty
server from node-js:
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.use('/api', router);
app.listen(port);
console.log('Listening on ' + port);
On my site i am trying to retrieve the json by using curl:
<?php
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/"); // i removed the ip from my server for safety reasons
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print "output=";
print_r($ouput);
// close curl resource to free up system resources
curl_close($ch);
?>
Note: sending a get request above from postman i receive the answer i want. I don't know what is wrong. Thx in advance.
Also, curl is a blocking function.. right?
Both "servers" are on the same server. I don't know if is an error like cross-server-origin of javascript
reason why you don't get response via php - wrong var name in print_r func
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
print "output=";
print_r($output); // missed t in output
curl_close($ch);
?>
Please read below my scenario..
I have been given a link.. On executing the link in web browser, message will be sent to the intended recipients .. But for my website I need the link to be executed in php as I would retrieve member name from db...
Steps....
Retrieve name from db
$URL = "ABC.com&msg=".$msg
(Execute the link)
/* do something
url = 'http://api.smsgatewayhub.com/smsapi/pushsms.aspx?user=stthomasmtc&pwd=429944&to=9176411081&sid=STMTSC&msg=Dear%20Sam,%20choir%20practice%20will%20be%20held%20in%20our%20Church%20on%20July%2031%20at%208:00%20pm.%20Thanks,%20St.%20Thomas%20MTC!&fl=0&gwid=2'
I am not sure how to execute a link without redirecting.. Hence cannot use header()
I tried using file_get_contents() but didn't work..
Can you please guide me.. Thanks!
Why not you are using AJAX,
As well through the AJAX you can also execute external link by using http client and can get the data and send it back in UI side.
once you retrieve the data in JSON/XML format then render the same.
Well, first of all you'd need the http:// part for file_get_contents to work:
$URL = "http://example.com&msg=".$msg
$result = file_get_contents($URL);
You can use the CURL to hit the URL after fetching the details from database.
PHP Manual Curl.
function get_http_request($uri, $time_out = 100, $headers = 0)
{
$ch = curl_init(); // Initializing
curl_setopt($ch, CURLOPT_URL, trim($uri)); // Set URI
curl_setopt($ch, CURLOPT_HEADER, $headers); //Set Header
curl_setopt($ch, CURLOPT_TIMEOUT, $time_out); // Time-out in seconds
$result = curl_exec($ch); // Executing
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
$result = ""; // Executing
}
curl_close($ch); // Closing the channel
return $result;
}
I am trying to access another site using a POST request through ajax. So the access flow became :
AJAX request -> PHP CURL -> www.somedomain.com
This is the code for the AJAX request. I guarantee it passes the parameters correctly:
$("#new_access_token").submit(function(ev){
$.ajax({
url : "back_access/access_code.php",
type : "POST",
data: "access_token[app_id]=601&access_token[subscriber_num]="+$("#input-phone-number").val(),
success : function(res){
console.log(res);
}
});
return false;
});
The php curl script is here (access_code.php):
$ch = curl_init();
$url = "http://developer.globelabs.com.ph/oauth/request_authorization";
$data = array("access_token" => array(
'app_id' => $_POST['access_token']['app_id'],
'subscriber_number' => $_POST['access_token']['subscriber_number']
));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
It returns an error of "500". With the correct parameters in terminal curl and Advanced Rest Client, it returns the page. However, this script does not. How do I control the parameters?
because you are posting multidomensional array so You'd have to build the POST string manually, rather than passing the entire array in .. you should add curl header with a form Type multipart and other relative things like accept , content-length etc
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
if you serialize or jsone_encode the whole field you can send the data but in this case you also need to capture the data and unserialize/json_decode it from server end.
Im trying to send a GET or POST request from PHP (CLI), to a Node.js/Sockets.IO application, using only basic cURL. This is what i have so far, i can see the response coming in to node.js (from the cli), but can not get any farther. Currently i only want the parameters sent to the console. (I can expand on that later)
Any help would be great!
(FYI: I did look at this, Socket.io from php source, but need more help. Exact code would be great)
PHP
$qry_str = "?msg_from_php=This_is_a_test123&y=20";
$ServerAddress = 'http://10.1.1.69/socket.io/1/websocket/TICWI50sbew59XRE-O';
$ServerPort = '4000';
$TimeOut = 20;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ServerAddress. $qry_str);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_PORT, $ServerPort);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $TimeOut);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
// not sure if it should be in an array
//$data = array('msg_from_php' => 'simple message!');
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$content = trim(curl_exec($ch));
curl_close($ch);
echo " Sent! Content: $content \r\n";
Node.JS
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.configure('production', function(){
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 1);
io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
io.set("polling duration", 30);
});
server.listen(4000); // 80,443, 843, 4000, 4001
io.sockets.on('connection', function (socket) {
socket.on('msg_from_php, function (data) {
console.log(data);
});
});
You're trying to make an ordinary HTTP connection to a socket.io server, but socket.io doesn't speak plain HTTP; it uses at the very least a specialized handshaking protocol, and if it uses websocket transport it won't be using HTTP at all. AFAIK there's no PHP implementation of a socket.io client.
Fortunately, it looks like your PHP application needs to send to your node application on its own terms, not the other way around, so all you need to do is use express to define a couple routes to implement a RESTful interface; your PHP app can then use cURL to POST to the URL corresponding to the appropriate route.