I am trying to use curl to solve cors issue with XMLHttpRequest while trying to get radio metadata (I cant use jQuery jsonp for this). I am not sure if curl can achieve this.
var xhr = new XMLHttpRequest;
xhr.onerror = function (e) {
console.error(e);
};
xhr.onreadystatechange = function () {
if (this.readyState == 4){
if(xhr_radioData.status == 200){
}
}
};
var url = 'http://stream.rockradio.si:9034/stats?sid=1&json=1;
var params = 'url='+url;
var curl = 'jsonp.php';
xhr.open("POST", curl);
xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
xhr.send(params);
json.php
<?php
$url = $_POST['url'];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'X-Requested-With: XMLHttpRequest'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 120);
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
echo "cURL Error #:" . $err;
}else{
echo ($response);
}
exit;
?>
I am getting an error:
cURL Error #:Failed to connect to stream.rockradio.si port 9034 after 2003 ms: Connection refused
Related
If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?
Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}
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 using facebook login using oauth. Sometime I am getting proper accessToken or sometime this kind of garbage values in accessToken
{"source":"uni","s":"s","p":{"z":"0","c":"0","i":"287"},"r": {"z":"1","c":"15239"},"node_id":"23.57.77.12"}.
Because of that my next requests to graph API fails. What is that thing and How do I handle this??
I have multiple domains ex. www.example.com, www.example12.com, www.example22.com etc.
I have created app for www.example.com on facebook and using it for all domains using the window.postmessage:
homepage.php (When user click on facebook login button):
if(!window.addEventListener){
window.attachEvent("onclick", processFacebookLogin);
}
else{
window.addEventListener("message", processFacebookLogin, false);
}
var width = 500;
var height = 500;
var left = ((window.innerWidth / 2) - (width / 2)) + window.screenLeft;
var top = ((window.innerHeight / 2) - (height / 2)) + window.screenTop;
winObj = window.open("http://www.example.com/fb-login?currentDomain=www.example12.com", "fbwindow", "height="+width+",width="+height+",top="+top+",left="+left);
function processFacebookLogin(e) {
winObj.close();
if(e.data != "error" && e.data != "missing_param"){
accessToken = e.data;
$.ajax({
async: false,
url: "UrlToProcessFacebookLogin",
type: "POST",
dataType: "json",
data:
{
"medium" :"facebook",
"accessToken" : accessToken
},
success: function(data)
{
//redirect to some another url
}
});
}
}
child window url page contains the following code fbLoginController.php:
The above window.open contains the indexAction url of fbLoginController (I am using Zend Framework):
public function indexAction()
{
$communityDomain = preg_replace('#^https?://#', '', $_GET['community']);
$fbLoginUrl = "https://www.facebook.com/v1.0/dialog/oauth?client_id=FbAppClientId&scope=AllRequiredScopes&auth_type=rerequest&return_scopes=true&display=popup&redirect_uri=http://www.example.com/fb-login/fb-response?community=".$communityDomain;
$this->_redirect($fbLoginUrl);
exit;
}
public function fbResponseAction()
{
$arrParams = $this->_getAllParams();
$code = $arrParams['code'];
$communityDomain = $arrParams['community'];
$grantedScopes = $arrParams['granted_scopes'];
$error = $arrParams['error'];
if(!empty($error))
{
echo "<script>window.opener.postMessage('error', 'http://".$communityDomain."');</script>";
exit;
}
if(empty($communityDomain) || empty($grantedScopes))
{
echo "<script>window.opener.postMessage('missing_param', 'http://".$communityDomain."');</script>";
exit;
}
$curlUrl = "https://graph.facebook.com/v1.0/oauth/access_token?client_id=FbAppClientId&client_secret=FbAppClientSecret&code=" . $code . "&redirect_uri=http://www.example.com/fb-login/fb-response?community=" . $communityDomain;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
curl_setopt($ch, CURLOPT_POST, 0);
$curlResponse = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
parse_str($curlResponse,$parsedStr);
echo "<script>window.opener.postMessage('".$parsedStr['access_token']."', 'http://".$communityDomain."');</script>";
exit;
}
for proper understanding I have put each and every line of code in this question.
Hi every one,
I have a login form which has mail id and password, on submit it should call an api which inturn generates a auth token. I have used POST method in Php curl but getting the following error.
Apache Tomcat/6.0.36 - Error report
.. some html styles..
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method
and this is my ajax call..
function callapi()
{
data = new Object();
var email= document.getElementById("input01").value;
var pwd=document.getElementById("input02").value;
if(email != ""&& pwd != "")
{
data.Email = email;
data.Pwd = pwd;
}
jQuery.ajax({
url: "http://localhost/stackato/nlogin.php",
type: "POST",
dataType:"json",
data:data,
error: function (data) {
alert('error--'+data);
},
success: function (data) {
if(data=="invalid")
{
}
else
{
window.location.href="finalstackatolists1.html";
}
}
});
}
and this is my curl php page
<?php
header('Content-type: application/json');
$url = $_SERVER['REQUEST_URI'];
$scriptname = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$mail=$_POST["Email"];
$pwd=$_POST["Pwd"];
$action = $_POST["action"];
$nurl = str_replace($scriptname,"...the api...",$url);
//open connection
$ch = curl_init();
$data = array("username" => $mail, "password" => $pwd);
$req_data = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//execute post
if( ! $result = curl_exec($ch)) {
die(curl_error($ch));
curl_close($ch);
}
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '500')
{
header("Status: 500 Server Error");
}
curl_close($ch);
echo $result;
?>
(I tried it in REST-Client and the token has been generating)
Please help me to solve this.. thanks in advance..
You have to specify that the posted data is of type JSON
add this line to your curl code
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/json"));
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);