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.
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.
I tried to make a request to my nodeJS using CURL from PHP.
Here is my code:
$host = 'http://my_ip:8080/ping';
$json = '{"id":"13"}';
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
$data = curl_exec($ch);
var_dump($data);
But it doesn't work. I received bool(FALSE) in data var.
NodeJS:
app.use(router(app));
app.post('/ping', bodyParser, ping);
port = 8080;
app.listen(port, webStatus(+port));
function* ping() {
console.log(this.request.body);
this.body = 1;
}
I tried with NodeJS Http-post and it works:
http.post = require('http-post');
http.post('http://my_ip:8080/ping', { id: '13' }, function (res) {
res.on('data', function (chunk) {
console.log(chunk);
});
});
Is it something wrong with PHP code?
PS: The CURL is included in PHP.
Your ping function is not well implemented I think.
Also, you need to call the send method in order to send the HTTP response.
You should declare the function like this :
app.use(bodyParser); // You can use a middleware like this too.
app.post('/ping', ping);
function ping (req, res) {
console.log(req.body); // Since you use `bodyParser` middleware, you can get the `body` directly.
// Do your stuff here.
res.status(200).send('toto');
}
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);
?>
I tried to integrate node js with my application, I have just test the http server It works well, but when I use https server as following with my index.php to subscribe the message, This does not work.
Start a server
var https = require('https'),
faye = require('faye');
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
var server = https.createServer(options),
bayeux = new faye.NodeAdapter({mount: '/'});
bayeux.attach(server);
server.listen(1337);
Create a client
<script src="faye-browser-min.js"></script>
<script>
var client = new Faye.Client('https://localhost:1337/');
client.subscribe('/messages/*', function(message) {
alert('Got a message:');
});
</script>
Send messages
I used Faye client to push message in test.php .
$adapter = new \Nc\FayeClient\Adapter\CurlAdapter();
$client = new \Nc\FayeClient\Client($adapter, 'https://localhost:1337/');
$client->send("/messages/test", array("name" => "foo"), array("token" => "456454sdqd"));
Thank you,
Please tell me how to check is there any error on server side.
I fixed issue my self, The issue was not in server side. It was in php Faye Client side. That Php Client works fine for HTTP server, but I need to use it for HTTPS server. I have done following changes then It works fine.
/vendor/nc/faye-client/src/Nc/FayeClient/Adapter/CurlAdapter.php
public function postJSON($url, $body)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body),
));
curl_exec($curl);
curl_close($curl);
}
I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8080)
The curl request I have written in my php code is:
$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;
I can do a curl request :
curl http://my-ip-address:8080/
from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".
Kindly help!
If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.
Two things that might be wrong:
Your Flask server has a firewall that doesn't allow external connections.
You are connecting using an private network IP address rather than a public IP address.
For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.
try to set your port with curl options like this:
curl_setopt($ch, CURLOPT_PORT, 8080);
so your signed url will be:
$signed_url = "http://my-ip-address";
I use this code for my work and worked :)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
the key is CURLOPT_POSTFIELDS