I have to send a json response from a cURL call.
The user send me a "test" variable to file.php.
On my php file, I use this code
$arr = array($arr = array('test' => 'ok'));
echo json_encode($arr);
And this for the cURL call
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "12341234123412342" }'
Here is the answer
[{"test":null}]
What's the good way to get de POST variable and treat it in my php file?
Thanks
EDIT
Just in case, the problem comes from the cURL call. Here's the correct syntax:
curl -H "Content-Type: application/json" -X POST -d "{\"test\":\"12341234123412342\"}" http://www.domain.com/WS/file.php
Ur question is kinda confusing :)
so ur User sends u a variable in file.php
and u have to curl with that variable ?
why not just
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "$_POST['USER_INPUT_VALUE']" }'
or am i missing something ?
Thanks for your help.
You're right, it might be confusing. I have to add some new details and give a better example.
The user execute that script in a file test_curl.php:
// test_curl.php
$url = "http://www.domain.com/WS/file.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'test' => '12345'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
echo $contents;
curl_close($ch);
Here's the file.php
// file.php
$arr = array($arr = array('test' => $_POST['test']));
echo json_encode($arr);
I recieve the POST variable and it works. Here's what $contents recieve in test_curl.php
{"test" => "12345"}
New fact, it works with test_curl.php. I've got the good answer but when do it in command line with that code...
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "12345" }'
...I've got this answer:
[{"test":null}]
And finally, my question is why the response is null when I make my call in command line?
That won't work.
In your post data you are sending a json/application content type. Inside the server, you are expecting content from a variable called test, which should only exists in a normal form key valued body, which is not the case.
So, you need to json_decode directly the raw body of the post data content, then access the test key inside it, as such:
$raw_body = file_get_contents('php://input');
$json = json_decode($raw_body);
$arr = array($arr = array('test' => $json['test']);
echo json_encode($arr);
Related
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);
I have an existing PHP script, which essentially connects to 2 databases each on a different server and performs a few MySQL queries on each. The ultimate results are stored in a data array which is used to write said results into a JSON file.
All of this works perfectly. The data is inserted into the mysql table correctly and the JSON file is exactly the way it should be.
However, I need to add a block to the end of my script that makes a POST request to one of our affiliate's API and upload the info there. We're currently manually uploading this JSON file to the api instance but we have the configuration data for their server to use in a POST request now so that when this script is run it automatically sends the data rather than us having to manually update it.
The main thing is I'm not exactly sure how to go about that. I've started with code for doing this but I'm not familiar with cURL so I don't know the best way to structure this in php.
Here is an example the affiliate gave me in cURL command line syntax:
curl \
-H "Authorization: Token AUTH_TOKEN" \
-H "Content-Type: CONTENT_TYPE" \
-X POST \
-d '[{"email": "jason#yourcompany.com", "date": "8/16/2016", "calls": "3"}]'
\
https://endpoint/api/v1/data/DATA_TYPE/
I have my auth token, my endpoint URL and my content type is JSON, which can be seen in my code below. Also, I have an array instead of the example for the body above.
and here's the affected part of my code:
//new array specifically for the final JSON file
$content2 = [];
//creating array for new fetch since it now has the updated extension IDs
while ($d2 = mysqli_fetch_array($data2, MYSQLI_ASSOC)) {
// Store the current row
$content2[] = $d2;
}
// Store it all into our final JSON file
file_put_contents('ambitionLog.json', json_encode($content2, JSON_PRETTY_PRINT ));
//Beginning code to upload to Ambition API via POST
$url = 'endpoint here';
//Initiate CURL
$ch = curl_init($url);
//JSON data
$jsonDataEncodeUpload = json_encode($content2, JSON_PRETTY_PRINT);
//POST via CURL
curl_setopt($ch, CURLOPT_POST, 1);
//attach JSON to post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncodeUpload);
//set content type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//execuate request
$postResult = curl_exec($ch);
So, like I said, nothing about the file or the data needs to be changed, I just need to have this cURL section take the existing array that's being written to a JSON file and upload it to the API via post. I just need help making my php syntax for curl match the command line example.
Thanks for any possible help.
Have you tried with file_get_contents ( http://en.php.net/file_get_contents ).
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
I have found the answer on stackoverflow How to post data in PHP using file_get_contents?
Here is worked example of code. Check $err may be it will be helpful.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST('data'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
Hi i am testing a scenario for REST web service for mobile app.During testing i need to send an array to my php programme using post method. which i am doing through cURL console. rest of the thing is working fine except passing an array. Please suggest any changes.
following code i am passing in cURL console
C:\curlw32>curl -H "Content-Type: application/json" -X POST http://localhost/slim-login/api/submit -d "{\"specialtyCheckbox\":\"[1,2,3]\"}"
and here is the php code for catching it
$request = Slim::getInstance()->request();
$onsubmit_content = json_decode($request->getBody());
$spec=$onsubmit_content->specialtyCheckbox;
echo json_encode(count($spec));
Here the length of the array it is showing 1.
dont use quotes around your array (if you want to send a json array ):
"{\"specialtyCheckbox\":[1,2,3]}"
Can you try passing your array through a PHP script( using CURL)
$ch = curl_init ($url); // your URL to send array data
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); // Your array field
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
print_r($result);
If you wanna pass the array over the CURL call the answer is very simple. Put all the input parameters in array like-
$post = array('prgmCode'=>'3',
'userStateCode'=>'TA',
);
If you need to pass an input array on this you can set
`$chkBoxArr = array(1,2,3,4);
$post = array('prgmCode'=>'3',
'userStateCode'=>'TA',
'chkBoxArr'=>$chkBoxArr
);`
You can use function http_build_query() to make a query string from the array.
`$data = http_build_query($post);`
And set the data to your curl
`curl_setopt($curlSession, CURLOPT_POSTFIELDS, $data);`
Check the request in the server side. Done. :) :)
Please try This
curl -d '{"previous_questions":"['hello', 'world', 'finally']"}' -H "Content-Type: application/json" -X POST http://localhost:5000/quizzes
According to the author of faye i can send messages from any platform
and the format to post a message with curl is:
curl -X POST http://192.168.1.101:8000/faye -H 'Content-Type:
application/json' -d '{"channel":"/foo","data":{"hello":"world"}}'
I format the previous line to be used in php
$data = array("channel" => "/one", "result" => "Hello World from PHP!!");
$data_string=json_encode($data);
$ch = curl_init('http://192.168.1.101:8000/faye');
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);
Somehow the subscriber to channel one DOES not GET the result
the publish function in java script works seamlessly (see line below)
var publication = client.publish('/one',{ result: 'Hello World from JS'});<br/>
Please let me know what is missing or my mistake thanks
This one works for me:
$data = array("channel" => "/one", "data" => array ("result"=>"HelloWorld from PHP!!"));
$data_string=json_encode($data);
$ch = curl_init('http://localhost:8000/faye');
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'));
echo $result = curl_exec($ch);
Well title says all I guess.
I've tried to print_r($_SERVER) but my 'post-request' I made with fiddler doesn't show up.
I'm really out of my mind after trying about 1 hour now :S
What I actually want is to send a POST request with JSON in the request-body. Then I want to json_decode(request-body); This way I can use the variables to reply. So I don't need to put my variables in the URL
Edit:
This is my POST
$url = 'http.........jsonAPI/jsonTestAPI.php';
$post = array("token" => "923874657382934857y32893475y43829ufhgjdkfn");
$jsonpost = json_encode($post);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
$response = curl_exec($ch);
curl_close($ch);
Try file_get_contents('php://input'); or PHP global $HTTP_RAW_POST_DATA.
the easiest way to get that done would be to put your json into a hidden input-field and then have the containing form being submitted using POST.