AJAX rerouting from CURL with associative array parameters - php

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.

Related

sending json via php curl but not getting a response

I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.
Here is the php:
<?php
$post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);
$transfer = json_encode($post);
$ctrl = curl_init();
curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
curl_setopt($ctrl, CURLOPT_POST, TRUE);
curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ctrl);
curl_close($ctrl);
$response = json_decode($response);
echo $response;
?>
If I were to echo $transfer it would read:
{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
"output":"4"}
}
I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:
{"message":"An unknown internal error occured","success":false}
How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?
Try setting the header to say you are sending JSON...
curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($transfer))
);
For the HTTPS, you may also need...
curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);
You also may try...
curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1);

get specific data from REST API

I want to get specific data from rest api after user login using cookie auth but I end up with Field 'fieldname' does not exist or this field cannot be viewed by anonymous users.
Below you can see the code I wrote in ajax and php to get data. I know my script is probably awful as I used curl request for the first time so bear with me, I want someone to tell me where I am doing wrong or better explain to me how to get and post data to server with curl and get and specific data display would be appreciated.
$('#user-profile').click(function(){
$.ajax({
type: "POST",
url: "jiraticket.php",
data: $('#login-form').serialize(),
success: function(data){
alert(data);
}
});
});
and here is the script
<?php
session_start();
$url = 'http://base-url/rest/api/2/search?jql=issuetype%20=%20Epic%20AND%20status%20in%20(%22In%20Progress%22,%20Backlog,%20%22On%20hold%22,%20%22To%20Do%22)';
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_HEADER, 0);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
if(isset($_COOKIE['JSESSIONID']))
$cookie_string='JSESSIONID='.$_COOKIE['JSESSIONID'];
else
$cookie_string="";
curl_setopt($curl_session, CURLOPT_HTTPHEADER, array('Content-Type: application/json' ,'Authorization: Cookie'), array('cookie:'.$cookie_string));
$response = curl_exec($curl_session);
curl_close($curl_session);
if ( !$response ) {
die('Nothing was returned.');
}
$result = json_decode($response, true);
print_r($result);
$response printing "errorMessages":["Field 'issuetype' does not exist
or this field cannot be viewed by anonymous users."]
Well, it means the API does not want to give you the value of issuetype.
Might be a typo or something, but that's not an error with your curl call, it's a problem with the API provider

php+curl to send a post request with fields

trying to send post request to api, to get an image back.
example url:
https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php?user=1003123&format=png&cloudid=asdasdasd&pass=123123123
the above url works fine in the browser,
the api doesnt care if the request is get/post,
result of my code is always 'invalid input'.
code:
$url='https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php';
$u = rand();
$p = rand();
$fields = array(
'user'=> urlencode($u),
'pass'=> urlencode($p),
'format'=> urlencode('jpg'),
'cloudid' => urlencode('test')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
on a side note: is there a way to debug the request in order to see what is being sent ?
The URL provided isn't working for POST request. Here is resulting screenshot (I tried using Advance Rest Client)
However Its working perfectly with GET method. So you can continue using GET request method to generate QR code.
I agree that GET isn't much secure compare to POST method but in your case while requesting from curl user won't get to know about such URL parameters (userid, password). Because curl request will be sending from your web server and not from client/user's browser.
Later you can just output the response image you got from the api.

Post JSON data to external URL

How do you post JSON data as a url string to an external url (cross domains) and bypass Access Control?
Here is a jquery .ajax post request that won't work sending to an external url because of Access-Control-Allow-Origin:
var json = JSON.stringify(object);
$.ajax({
type: 'POST',
url: externalurl,
data: json,
dataType: 'json',
success: function(data){console.log(data);},
failure: function(errMsg) {
console.log(errMsg);
},
});
I have received a suggestion to POST the data to the same domain and 'pass on the request' to the external domain, though this solution doesn't make sense to me. I am looking for the most secure solution. Any help would be much appreciated.
I did this not too long ago in PHP. Here's an example of "passing the request". (You'll need to enable PHP cURL, which is pretty standard with most installations.)
<?php
//Get the JSON data POSTed to the page
$request = file_get_contents('php://input');
//Send the JSON data to the right server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://location_of_server.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$data = curl_exec($ch);
curl_close($ch);
//Send the response back to the Javascript code
echo $data;
?>
One way to bypass the Same-Origin policy is to use cURL to do the actual transmitting.
I'll give an example using PHP, but you could easily do this on any server side language.
Set up a script on your server, for example send.php
First you point your ajax to send.php
var json = JSON.stringify(object);
$.ajax({
type: 'POST',
url: send.php,
data: json,
dataType: 'json',
success: function(data){console.log(data);},
failure: function(errMsg) {
console.log(errMsg);
},
});
Then your php script to forward it:
<?php
// Initialize curl
$curl = curl_init();
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'field1=arg1&field2=arg2'
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
?>

Post to another page within a PHP script

How can I make a post request to a different php page within a php script? I have one front end computer as the html page server, but when the user clicks a button, I want a backend server to do the processing and then send the information back to the front end server to show the user. I was saying that I can have a php page on the back end computer and it will send the information back to the front end. So once again, how can I do a POST request to another php page, from a php page?
Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:
// where are we posting to?
$url = 'http://foo.com/script.php';
// what post fields?
$fields = array(
'field1' => $field1,
'field2' => $field2,
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
Also check out Zend_Http set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).
2014 EDIT - well, it's been a while since I wrote that. These days it's worth checking Guzzle which again can work with or without the curl extension.
Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).
Sample snippet:
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name),
'email'=>urlencode($email)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Credits go to http://php.dzone.com.
Also, don't forget to visit the appropriate page(s) in the PHP Manual
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$fetch_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );
curl_close($ch);
You can also look into the PHP HTTP Extension.
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe
http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself
http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.
Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
Solution is in target="_blank" like this:
http://www.ozzu.com/website-design-forum/multiple-form-submit-actions-t25024.html
edit form like this:
<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">
And use this script:
<script type="text/javascript">
<!--
function doubleSubmit(f)
{
// submit to action in form
f.submit();
// set second action and submit
f.target="_blank";
f.action="../booking/vytvor.php";
f.submit();
return false;
}
//-->
</script>
Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();
CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.

Categories