PHP - How to get POSTFIELDS sent with CURL? - php

I am using curl to call API method (Symfony2, FOSRestBundle) and wonder how can I get the data sent in POSTFIELDS?
$_params = [];
$data_string = json_encode($_params);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $_method);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$json = curl_exec($curl);
If I send something in for example CURLOPT_HTTPHEADER I can get it later in controller using
$request->headers->get("some_variable");
But how can I access $data_string? I have dumped almost every possible variable and still nothing.

To retrieve a POST value in symphony you can use:
$request->request->get('key', 'default value');
Assuming $_params is a valid json object, you need to url-ify the data for the POST, i.e.:
$post_fields = http_build_query(json_decode($_params));
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); </s>
To retrieve all post values in symphony you can use:
$params = $this->getRequest()->request->all();
$params['val1'];
$params['val2'];

As I understand your first code snippet, you're effectively trying to POST a JSON string? It was my understanding that your PHP code wouldn't work as per the PHP documentation for CURLOPT_POSTFIELDS:
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
But as per this blog post apparently you can do it your way.
Anyway, back to your question. To get the full content of a request, you would do:
$content = $request->getContent();
And to then decode the JSON you would do:
$params = json_decode($content);
Another StackOverflow answer covers this. About the only thing I'd say is that you need to correctly set the MIME type when you're sending the post, e.g.
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]);
The previously mentioned blog post covers this.

Related

CURL Request to Laravel API Returns NULL Values

I'm attempting to send an array of objects as part of a JSON request with curl. The request must use json_encode in order to be sent by curl. However I am running into an issue on the Laravel API that is receiving it. Any attempt to get an object from the Request Laravel object returns null i.e.:
$request->order_number;
$request->items;
This is the case for normal fields and the array of objects I am also sending. The curl appears as:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
What is the mistake I am making?
EDIT:
To provide more specific information, here is the json_encode var dumped (some omissions):
string(694) "{"order_number":"11111","items":"[{"id":"1005","name":"UpRight 011238-004 Washer, Split Lock","sku":"","quantity":1,"price":0.01}]"}"
The solution ended up being rather convoluted:
public function postOrderInformation(Request $data) {
$request = json_decode(json_encode(json_decode($data->getContent(), true)));
}
This created a useable object from which the data could be extracted from the laravel Requets object. If anyone has a more elegant/less ugly solution, please post it.

Slack Slash Command - Getting user icon URL with username (PHP)

I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.
I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.
However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?
This is how far I got:
$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($fields))
);
$profile = curl_exec($slack_call);
curl_close($slack_call);
I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?
If anybody recommends doing this a different way, I would appreciate any advice as well.
Thank you so much!
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).
The query string for application/x-www-form-urlencoded is formatted like a get URL string.
https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1
Just request that URL and you will retrieve the data.
The POST body format will use a similar code to what you have above.
$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";
$ch = curl_init($loc);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($error = curl_errno($ch)) { echo $error; }
//close connection
curl_close($ch);
echo $result;

Http post request with JSON String in PHP

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.

How to make a JSON Curl request to an api url, getting null

This should be simple I think but I just can't fathom it.
I need to make a request to a url in the following format:
http://ratings.api.co.uk/business/{lang}/{fhrsid}/{format} where lang will be set to en-GB the fhrsid is an identifier and format is json.
I tried the following but I am just getting null in return:
$data = array("lang" => "en-GB", "fhrsid" => "80928");
$data_string = json_encode($data);
$ch = curl_init('http://ratings.api.co.uk/business/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)) );
$Jsonresult = curl_exec($ch);
curl_close($ch);
var_dump(json_decode($Jsonresult));
Any help gratefully received
You are currently posting the data to the URL, while you say you want to put the data in the URL itself.
I.e. now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json, but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json.
Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.
Sending data as arguments is different than sending it within the URL.
If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format}, then you must make your curl_init string match that format.

How do I get all my 'content' from the Request Body in a POST request?

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.

Categories