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);
Related
cURL is new to me. I'm trying to integrate an api via PHP cURL. The api that I'm trying to access requires that parameters be sent as key-value pairs, not json. Their example cURL request in their docs is:
curl -i -X POST -d 'api_key=my_api_key' -d
'email=john#doe.com' -d "first_name=Joe" -d "last_name=Doe" -d
"cust_id=cus_401"
https://serviceurl.com/api/create
My code is apparently sending empty parameters to their api.
$service_url = 'https://serviceurl.com/api/create';
$curl = curl_init($service_url);
$email = $this->session->userdata('email');
$postArray = array(
'api_key' => 'my_api_key',
'email' => $email,
);
$curl_post_data = $postArray;
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
echo $curl_response;
echo $info;
Any advice would be greatly appreciated.
your curl php code is sending the data in multipart/form-data format, but as evident by their cli invocation example, their api wants the data in application/x-www-form-urlencoded format.
as explained by the curl_setopt docs, when you give CURLOPT_POSTFIELDS an array, it will automatically be encoded to multipart/form-data, if you give it a string, application/x-www-form-urlencoded will automatically be assumed, and is what their curl cli invocation is using.
lucky for you, PHP has a dedicated function for encoding arrays to application/x-www-form-urlencoded format, called http_build_query, thus
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($curl_post_data)); will fix your issue of apparently sending empty parameters.
also, if there is a problem setting any of your options, curl_setopt will return bool(false), which your code is completely ignoring, and would go unnoticed, you should fix that, consider using an error-catching setopt wrapper, like
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
$ret=curl_setopt($ch,$option,$value);
if($ret!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . $ch .'. curl_error: '.curl_error($ch) );
}
return true;
}
I need to send an XML string via HTTP POST to another server using the settings below...
POST /xmlreceive.asmx/CaseApplicationZipped HTTP/1.1
Host: www.dummyurl.co.uk
Content-Type: application/x-www-form-urlencoded
Content-Length: length
XMLApplication=XMLstring&byArray=base64string
I'm guessing I need to set this up via cURL or maybe fsockopen.
I've tried the following but not having any luck at getting it to work.
$url = "http://www.dummyurl.co.uk/XMLReceive.asmx/CaseApplicationZipped";
$headers = array(
"Content-Type: application/x-www-form-urlencoded"//,
);
$post = http_build_query(array('XMLApplication' => $XML, 'byArray' => $base64));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "response: ".$response;
The remote server gives the following response...
"Object reference not set to an instance of an object."
Not enough rep yet to comment, so I'll post this as an answer.
PHP's cURL automatically send the Host (from $url) and the Content-Length headers, so you don't need to specify those manually.
A handy function exists for building the $post string: http_build_query. It'll handle properly encoding your POST body. It would look something like
$post = http_build_query(array('XMLApplication' => $XML, 'byArray' => $base64));
If you want to log out the headers you received, check the curl_getopt function.
As for the error you received, it seems like you're passing the remote site things it doesn't expect. I can't speak for what you're passing or what the site's expecting, but Input string was not in a correct format seems to imply that your $XML is not formatted correctly, or is being passed as an incorrect parameter.
I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON.
But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?
These are my test files:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
test.php:
var_dump($_POST);
The response that I get is:
array(0) { }
You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
same questions: 1 2
Here is my code,
$url= 'http://dummyhost:8080/admin/EditSubscriber?jsonString={"sub_Id":3,"sub_Fname":"messi","sub_Lname":"lionel"}';
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
at the end of url JSON string is concatenated according to server requirement
but in response there is nothing i get in response variable.
What is wrong with this as when i make this request using chrome extension it shows me the result updated. And when i use the $url= "http://dummyhost:8080/admin/ViewSubsriber?jsonString={"sub_Name":"messi","sub_Password":"password"}";
i get the desired result.
i've used curl as well'
i've used Curl as well like this
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
but the same result i get that is nothing
If you have created JSON string at your own keep following things in mind:
Space in string might result in unnatural behavior from server so for each of the varible or atleast for strings use
urlecode(yourvariable);
then chek the string online wether the JSON string is valid or not like this
http://json.parser.online.fr/
Like Brant says use
$json = file_get_contents('php:://input');
for raw data instead of using the empty $data_string="";
Your posted variable, $data_string, is empty. You are using POST and sending empty data, but then also sending a query string. It seems you are mixing GET and POST methods here. You need to actually post your JSON string in the posted data.
If you are posting raw JSON string using application/JSON content type, the post data will need to be read from raw input like this
$json = file_get_contents('php:://input');
This is because $_POST is only automatically populated by PHP for form-encoded content types.
I would also recommend sticking with curl for such usage.
:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.