Sending messages from PHP to Node.js
The suggestion seems to be to talk to node through the HTTP interface, just as any other client does. You can talk to node via HTTP using cURL in php
See: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc/216933a076ac2595?pli=1
In particular, see this post from Matt Pardee
I faced a similar problem with wanting to keep users informed of a new
note added on to a bug, and similar notifications that could really
only be effectively sent from PHP to my Node server. What I did
follows (apologies if this gets all garbled and unformatted in
sending, if it does, I'd be happy to paste the code somewhere else):
First, you'll need to use cURL from PHP. I wrote a function for my
class like this:function notifyNode($type, $project_id, $from_user, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_PORT, 8001);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_POST, true);
$pf = array('f' => $type, 'pid' => $project_id, 'user_from' => $from_user,
'data' => array());
foreach($data as $k => $v) {
$pf['data'][$k] = $v;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pf));
curl_exec($ch);
curl_close($ch);
}
You'll notice that I send the cURL request on the same server since
both PHP and NodeJS are running there, your mileage may vary. The port
I set this code to connect to is 8001 (this is the port my Node server
is running on, and the port the socket.io server connects to). This
sends a HTTP POST request with the post field encoded. This is all
pretty standard cURL stuff.In your Node app you probably have something like:
var server = http.createServer(function(req, res) {});
server.listen(8001);
var io = io.listen(server, { transports: ['websocket', 'flashsocket', 'xhr-polling'] });
...
well what we'll do here is expand on the http.createServer part, to
listen for connections coming from our local host ("127.0.0.1"). The
createServer code then becomes:var server = http.createServer(function(req, res) {
// Check for notices from PHP
if(res.socket.remoteAddress == '127.0.0.1') {
if(req.method == 'POST') {
// The server is trying to send us an activity message
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, [[ "Content-Type", "text/plain"]
, ["Content-Length", 0]
]);
res.write('');
res.end();
//sys.puts(sys.inspect({fields: fields}, true, 4));
handleServerNotice(fields);
});
}
}
});
From there you can implement your handleServerNotice function..
function handleServerNotice(data) {
...
}
etc etc. I haven't tested this in a while, and in fact that code block
was commented out on my node server, so I hope what I've pasted here
works - in general this concept is proven and I think it'll work for
you. Anyway just wanted to be sure you knew it's been a few months so
I'm not sure exactly why I commented out. The code I wrote took a
little research -- like setting the 'Expect:' header in cURL -- and I
was pretty excited when it finally worked. Let me know if you need any
additional help.Best,
Matt Pardee
Sending data from php to nodejs server
Any reason you can't use curl?
$ch = curl_init('http://yournodehost/path');
curl_exec($ch);
Depending on the requirements of your request you can set the appropriate curl options.
- http://us2.php.net/curl_init
- http://us2.php.net/curl_setopt
Comunicate NodeJs with PHP and viceversa
With PHP:
You can save a random generated key in the database, associated with user's ip, user id and any other session information (time created, last active, expiration date...). Also, save that key in a cookie too.
With Node.js:
Read the cookie, find the key in the DB and check if the session is valid or not.
So, basically, instead of storing all info in PHP, use a shared storage like for example a DB.
PHP sending message to Node / Socket.IO server
im using http://elephant.io/ for comunication between php and socket.io, i have only problems with the time to stablish connection, 3 or 4 seconds to complete sending data.
<?php
require( __DIR__ . '/ElephantIO/Client.php');
use ElephantIO\Client as ElephantIOClient;
$elephant = new ElephantIOClient('http://localhost:8080', 'socket.io', 1, false, true, true);
$elephant->init();
$elephant->emit('message', 'foo');
$elephant->close();
PHP curl sending message to Node.js returns no result
You could make your php and your node communicate over HTTP.
You already have express installed in your node application so let's define a little API
Define a middleware
to ensure that is your php calling the node API
/**
* Secure the HTTP calls from PHP
* Return a 403 (forbidden) if no token given
* */
app.use(function (req, res, next) {
// Do your logic to secure your API if your node application is visible from the internet
// You don't want malicious people to send event as your php ;)
if(false) {
res.sendStatus(403);
return;
}
next(); // it's ok let the process continue
});
Define a simple route that answer on GET
http://localhost:3000/your/endpoint
app.get('/your/endpoint', function(req, res) {
io.sockets.emit('update');
res.sendStatus(200);
});
If you want to use the body of the HTTP request, you could use library like body-parser
that allow you to do stuff like below. This route answer at POST
http://localhost:3000/post/example
/** Enable the parsing of request body */
app.use(bodyParser.json());
app.post('/post/example', function(req, res) {
let body = req.body,
event = body.event,
data = body.data || {};
if(undefined === event) {
res.sendStatus(400);
return;
}
...
}
Related Topics
Pdo Multiple Fetching of Same Query
PHP Warning:Mysqli_Num_Rows() Expects Parameter 1 to Be MySQLi_Result, Object Given
Have Trouble Installing PHPmyadmin on PHP7 Apache/2.4.7 (Ubuntu)
PHP - a Db Abstraction Layer Use Static Class VS Singleton Object
Concatenate PHP Function Output to a String Like Variables
JSON_Encode or Remove Last Comma
How to Minify Js in PHP Easily...Or Something Else
How to Add PHP Pagination in Array'S
Sending Sms with Amazon Aws Services PHP
What Are the Best Practices for Catching and Re-Throwing Exceptions
Phpexcel Reader -- Help Required
Creating a Secure Login Using Sessions and Cookies in PHP
Location for Session Files in Apache/Php
Insert Non-English Decimal Points in MySQL
Is There a Function to Make a Copy of a PHP Array to Another