I am trying to send a post request through PHP cURL to my node.js server to then emit a message to the client. The server is working and setup as follows:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, qs = require('querystring')
app.listen(8000);
function handler(req, res) {
// set up some routes
switch(req.url) {
case '/push':
if (req.method == 'POST') {
console.log("[200] " + req.method + " to " + req.url);
var fullBody = '';
req.on('data', function(chunk) {
fullBody += chunk.toString();
if (fullBody.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function() {
// Send the notification!
var json = qs.stringify(fullBody);
console.log(json.message);
io.sockets.emit('push', { message: json.message });
// empty 200 OK response for now
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.end();
});
}
break;
default:
// Null
};
}
and my PHP is as follows:
$curl = curl_init();
$data = array('message' => 'simple message!');
curl_setopt($curl, CURLOPT_URL, "http://localhost:8000/push");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
The console says that json.message is undefined. Why is it undefined?
You're using querystring.stringify() incorrectly. See the documentation on querystring's methods here:
http://nodejs.org/docs/v0.4.12/api/querystring.html
I believe what you want is something like JSON.stringify() or querystring.parse(), as opposed to querystring.stringify() which is supposed to serialize an existing object into a query string; which is the opposite of what you are trying to do.
What you want is something that will convert your fullBody string into a JSON object.
If your body simply contains a stringified version of the JSON blob, then replace
var json = qs.stringify(fullBody);
With
var json = JSON.parse(fullBody);
try this code
<?php
$data = array(
'username' => 'tecadmin',
'password' => '012345678'
);
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init('https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
curl_close($ch);
Related
I am sending a steamid to node.js via curl and want to process it then.
But I am stuck at sending/retrieving an response...
Just as an ex. if the steamid can be processed -> then display return the processed value back to php.
app.js:
var server = require('http').createServer(handler)
var io = require('socket.io').listen(server)
server.listen(1777);
function handler(req, res) {
switch(req.url) {
case '/push':
if (req.method == 'POST') {
var request = '';
req.on('data', function(chunk) {
request += chunk.toString();
});
req.on('end', function() {
var json = JSON.parse(request);
console.log(json.steamid);
io.sockets.emit('push', { message: json.steamid });
res.end();
});
}
break;
};
};
php:
$ch = curl_init();
$data = array('steamid' => '76561141654816854');
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:1777/push");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
I am currently writing a piece of code to interface with an API in Python. Supplied by the company that hosts the API is a PHP script that logs into the API given the correct username and password, retrieved the current event ID (JSON format), and then logs out. This works perfectly.
Currently, I am in the process of writing a script in Python to do the very same thing, the current code is shown below. It logs in and out successfully, however, when it tries to retrieve the current event ID I get the status code 404, suggesting that the URL doesn't exist, despite this same URL working with the PHP code.
PHP Code:
define('BASE_URL', 'https://website.api.com/');
define('API_USER', 'username');
define('API_PASS', 'password');
$cookiefile = tempnam(__DIR__, "cookies");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
$loginParams = array(
'username' => API_USER,
'password' => API_PASS
);
$obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams);
if( $obj->success )
{
echo 'API login successful.' . PHP_EOL;
}
$obj = CurlGet($ch, BASE_URL . '/api/current-event-id');
echo 'API current event ID: ' . $obj->currentEventId . PHP_EOL;
// logout of the API
$obj = CurlGet($ch, BASE_URL . '/api/logout' );
if( $obj->success )
{
echo 'Logged out successfully.' . PHP_EOL;
}
curl_close($ch);
exit(0);
// -------------------------------------------------------------------------
// Functions
// -------------------------------------------------------------------------
// Run cURL post and decode the returned JSON object.
function CurlPost($ch, $url, $params)
{
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
// Run cURL get and decode the returned JSON object.
function CurlGet($ch, $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
Python Code:
import requests
BASE_URL = 'https://website.api.com/';
API_USER = "username";
API_PASS = "password";
headers = {'content-type': 'application/json'}
PARAMS = {'username':API_USER,'password':API_PASS}
session = requests.Session()
# Login
resp = session.post(BASE_URL + '/api/login',data=PARAMS)
if resp.status_code != 200:
print("*** ERROR ***: Login failed.")
else:
print("API login successful.")
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
print(resp.status_code)
print(resp.text)
# Logout
resp = session.get(BASE_URL + '/api/logout')
if resp.status_code != 200:
print("*** ERROR ***: Logout failed.")
else:
print("API logout successful.")
It's ideal to change BASE_URL to:
'https://website.api.com'
the code looks fine to me when compared to php and should normally work.(Shouldn't you be passing some kind of authentication like a token?).
try debugging your API using postman.
It turns out that my API will only accept cookies transferred in the header, so I wrote a slight hack that dumped the cookiejar into a string that could be sent in the header file.
cookies = json.dumps(requests.utils.dict_from_cookiejar(resp.cookies));
cookies = cookies.replace('"', '')
cookies = cookies.replace('{', '')
cookies = cookies.replace('}', '')
cookies = cookies.replace(': ', '=')
cookies = cookies.replace(',', ';')
headers = {'Cookie':cookies}
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
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');
}
I am building a asp.net core app with the debfault aspnetidentitycore plugedin, the only change is i added an action by modified the regiester method to a api, which means can be called by another app.
[HttpPost]
[AllowAnonymous]
public async Task<EngineResult<object>> RegisterByApi([FromBody]RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser
{
DisplayName = model.Name,
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return new EngineResult<object>(true) { Entity = new { sub = user.Id, name = user.DisplayName } };
}
return new EngineResult<object>(false) { Entity = string.Join(";", result.Errors?.Select(e => e.Description)) };
}
return new EngineResult<object>(false) { Entity = string.Join(";", ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage)) };
}
but when a php calls this api, i get a strange content-type, which is
application/json; boundary=------------------------e3f0ef0cc3e74f25
here is the php code
<?php
$data = [
"Name"=>"testname",
"Email"=>"123#testdomain.com",
"Password"=>"123qwe!#QWE",
"ConfirmPassword"=>"123qwe!##QWE",
"PhoneNumber"=>"12312321321",
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://xxxx/Account/RegisterByApi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
header_remove();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
anyone know what's happening here?
finally, it is a my php code issue, that not use a json data, replace the post data with a convert to josn will resolve this issue:
$payload = json_encode($data);
Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
My html file:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">
<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">
</FORM>
</body>
</html
I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// extra parameters for working with SSL URL's; eypeon (stackoverflow)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
I think it's coming form your html. You didn't put the form methode, so it send data by get.
And you show something only if you have post.
Try to do in the form method="post"
Edit
Bobby the main problem is that you don't have one problem but several in this code.
First if you don't do
<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">
the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).
Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.
Thirdly you don't use sprintf like you should.
echo sprintf(
$response['longUrl'],
$response['id']
);
Sprintf need to take a string format:
echo sprintf("%s %s" // for example
$response['longUrl'],
$response['id']
);
But do you know that you can do directly
echo $response['longUrl'] . ' ' . $response['id'];
You can concatenate string directly with . in php
curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl error: " . curl_error($ch);
}
As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.
You need to set CURLOPT_RETURNTRANSFER option in your code
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);