posting JSON DATA and request header using cURL PHP - php

This is my sample JSON Request
{
"Username":"admin",
"Password":"root123",
"PinCodeā€ : "hello321"
}
And also I want to post a request token as well, the request token has to be posted as a Request Header.
When I successfully sent those data and valid token, I need to receive a jSON response as below,
{
"Title": "Mr.",
"Name": "Pushkov",
"Age": "18"
}
My Question is,
How can I POST my above mentioned JSON data and the token in PHP cURL and display an error if the details are wrong in code igniter?
This is what I have done so far..and its not giving me the exact output im looking for and I couldn't figure out a way to send my token as a header request...
public function send_veri(){
$url='http://helloworld21.azurewebsites.net/api/member/login';
$ch = curl_init('http://localhost/apphome');
$data = array("Username" =>$this->input->post('un'), "Password" =>$this->input->post('pw'), "PinCode" =>$this->input->post('VerificationCode'));
$data_string = json_encode($data);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
//curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
}
once I run this, I could only get Username, Password and the PinCode only. I cannot post the request token in my header, in causing of that i cannot get the member detail response.

For Sending Data -
public function send_veri(){
$url='http://helloworld21.azurewebsites.net/api/member/login';
$ch = curl_init( $url );
$bodyData=json_encode(array()); // here you send body Data
$data = json_encode(array("Username" =>$this->input->post('un'), "Password" =>$this->input->post('pw'), "PinCode" =>$this->input->post('VerificationCode')));
curl_setopt( $ch, CURLOPT_POSTFIELDS, $bodyData );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array("headerdata: ".$data.",Content-Type:application/json"));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
}
Get Header data on Apache Server Code -
$hEAdERS = apache_request_headers();
$data = json_decode($hEAdERS['headerdata'], true);
echo $contentType=$hEAdERS['Content-Type'];
echo $Username = #trim($data['Username']);
echo $Password = #trim($data['Password']);
echo $PinCode = #trim($data['PinCode']);
It works for me.

Related

Unable to Upload a file to sharepoint library (Office 365) , gives error while creeating form digest

```` echo "<br/><br/>Generating Form Digest<br/>";
// Initialize curl for Getting the Form Digest
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxx.sharepoint.com/_api/contextinfo");
// Set curl Method
curl_setopt($ch, CURLOPT_POST, true);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Length: 0',
'Accept : application/json;odata=verbose',
// 'Authorization: Bearer ' . $access_token,
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $url_client);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo "<br/> Result of API Context :<br/>";
print_r(json_decode($result));
curl_close($ch);
echo "<br/><br/><br/>Uploading File<br/>";
// API URL with the file attached
$api_URL =
"https://xxxxxxxxxxxxxxxxxxxxxxxxxx.sharepoint.com/_api/web/GetFolderByServerRelativeUrl
('Documents')/Files/add(url='uploads/{$_FILES["fileToUpload"]["name"]}',overwrite=true)";
echo $api_URL;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $api_URL );
curl_setopt($ch, CURLOPT_POST, true);
// Set HTTP Header for POST request
// Set the headers in the curl object
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// 'Content-Type: application/x-www-form-urlencoded',
"Authorization: Bearer {$json_result->access_token}",
"Content-Length: {$filesize}",
"X-HTTP-Method: MERGE",
//"X-RequestDigest:",
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo "<br/> RESULT OF Upload file CURL<br/> " ;
// Convert result to JSon
$json_result = json_decode($result);
// Print Json Result
print_r($json_result);
// Close CURL
curl_close($ch);````
What I'm trying to do is to create a PHP webpage that will take a file ans an iput and upload it directly yo a shrepoint library
I'm generating access token before this code is executed
I'm getting the "404 unauthorized" error when form digest is generated, please help !!

linkedin oauth cant exchange auth code for access token

I am trying to use linkedin to get profile data of users, I get the authorization code from a button on login form that redirects to another page where I want to have some fields that fill with their name and such to create a user or login. I can't exchange the the auth token for an access one with my post. I get bad request or unauthorized responses. it says I am missing the required parameter "client_id", but it is obviously there ... Please take a look, thanks.
$code = $_GET['code'];
$data =array(
"grant_type" =>"authorization_code",
"code"=> $code,
"redirect_uri" => "http:\\localhost\index.php?doctor=linkedin",
"client_id" => "shh",
"client_secret" => "secret"
);
$str_data = json_encode($data);
//echo $str_data;
//function sendPostData($url, $post){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.linkedin.com/oauth/v2/accessToken');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$token = json_decode($result);
var_dump($token);
curl_close($ch); // Seems like good practice
function HandleHeaderLine( $curl, $header_line ) {
echo "<br>".$header_line; // or do whatever
return strlen($header_line);
}
LinkedIn expects ones POSTed field, as a query string. Try changing:
$str_data = json_encode($data);
to:
$str_data = http_build_query($data);
An Example from their documentation :
POST /oauth/v2/accessToken HTTP/1.1
Host: www.linkedin.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=987654321&redirect_uri=https%3A%2F%2Fwww.myapp.com%2Fauth%2Flinkedin&client_id=123456789&client_secret=shhdonottell
Hope that helps.

How to Add Recipient to Sendgrid v3 API with PHP

What I'm looking to do is add a single recipient to sendgrid when they signup on my site. Once they're added, I will then email the user and add them to a list.
But I'm having trouble adding the user to Sendgrid.
Their documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Recipients-POST) says to add a user you need to POST their details here:
https://api.sendgrid.com/v3/contactdb/recipients
add_user_new($email);
function add_user_new($email) {
$url = 'https://api.sendgrid.com/v3/contactdb/recipients';
$params =array( array(
//'name' => 'this is a reserved field',
'email'=> 'info#domain.com'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer api_key_here");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;
}
This is the response I get, not sure what I'm missing. The error they say is because the JSON is invalidly formatted.
string(51) "{"errors":[{"message":"request body is invalid"}]}
This is what my JSON looks like:
{"name":"hello#test.com"}
Encode your $json_post_fields variable do in JSON format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_post_fields));

Send JSON from one server and receive at another server

Hello I am passing an JSON array from one server say www.example1.com and I want to receive that data on another server say www.example2.com/test.php . I have tried this using cURL but I am not getting that data at the receiving. Following is my code
Code at Sender
$send_data = json_encode($myarray);
$request_url = 'www.example2.com/test.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'send_data='.$send_data);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);
Code at Receiver
if(isset($_REQUEST['send_data'])){
$userinfo = json_decode($_REQUEST['send_data'],true);
print_r($userinfo);
}
How do I fetch the data at receiver's end.
Try this method.
FILE: example1.com/sender.php
$request_url = 'www.example2.com/test.php';
$curl = curl_init( $request_url );
# Setup request to send json via POST.
$send_data = json_encode($myarray);
curl_setopt( $curl, CURLOPT_POSTFIELDS, $send_data );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($curl);
curl_close($curl);
# Print response.
echo "<pre>$result</pre>";
on your second page, you can catch the incoming request using file_get_contents("example1.com/sender.php"), which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("example1.com/sender.php")),1).'</pre>';
Use the following
FILE: example1.com/sender.php
<?php
header('Content-Type: application/json'); echo
json_encode(array('response1' => 'This is response1', 'response2' => 'This is response2', $_POST));
?>
FILE: example2.com/receiver.php
<?php
$request_url = 'http://www.example1.com/sender.php';
$sendData = array('postVar1' => 'postVar1');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'sendData=' . http_build_query($sendData));
print_r($response = curl_exec($curl));
curl_close($curl);
?>
You will get a JSON object as a cURL response.

POST to REST server by php

I want to make a post to a server I have by using php.
I was thinking in curl but all examples I find, urlfy data and I have to send a json file but not in the url.
I already have the json in an array : 'key'=>'value'...
I have to add headers, I think I can with this:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('HeaderName: HeaderValue','HeaderName2: HeaderValue2'));
but I don't knoe how to add my array and post it.
Any idea?
I need to add a json like this:
[{"a":"q",
"b":"w",
"c":[{
"e":"w",
"r":"t"
}]
}]
Here how you can post the data using CURL, and as you mentioned you already have a json you can do so as
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'your api end point');
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // $postfields is the json that you have
$request_headers = array();
$request_headers[] = 'HeaderName: HeaderValue','HeaderName2: HeaderValue2';
$request_headers[] = 'Content-Type: application/json','Content-Length: ' . strlen($postfields) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$response = curl_exec($ch);
curl_close ($ch);

Categories