Ruby Code:
# Turn hash input into JSON, store it in variable called "my_input"
my_input = { "itemFilter" => { "keywords" => "milk" }}.to_json
# Open connection to website.com
#http = Net::HTTP.new("website.com")
# Post the request to our API, with the "findItems" name and our JSON from above as the value
response_code, data = #http.post("/requests", "findItems=#{my_input}",
{'X-CUSTOM-HEADER' => 'MYCUSTOMCODE'})
my_hash = Crack::JSON.parse(data)
my_milk = my_hash["findItems"]["item"].first
PHP code:
$requestBody = json_encode(array("itemFilter" => array( "keywords" => "milk" )));
$headers = array ('X-CUSTOM-HEADER: MYCODE');
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, 'website.com/request/findItems=');
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
print_r($response);
Take a look at json_encode, json_decode and the cURL extension.
Found the problem.. Thanks for the input. I put a trailing slash where it was not required, and the json_encode was putting brackets around the encoding, and it didn't need them.
Related
I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.
The instructions I have for using an api gives two options.
One requires a zipCode input and one does not.
Using PHP I have successfully built a curl resource using curl_setop for the case that uses the zipCode but not the case that omits the zipCode. The case without the zipCode is supposed to have an extra option after the URL.
All I have been given for instructions is that the curl should be like:
curl -i -X POST -H "Content-Type:application/json" -H "authToken:12345" https://connect.apisite.com/api/v1/users -d'
[{
"firstName": "John",
"lastName": "Smith",
"emailAddress": {
"address": "johnsmith#test.com"
}
}]'
for the case without the zipCode
and with the zipCode
curl -i -X POST -H "Content-Type:application/json" -H
"authToken:12345" https://connect.apisite.com/api/v1/users '
[{
"firstName": "John",
"lastName": "Smith",
"emailAddress": { "address": "johnsmith#test.com" },
"homeAddress" : { "postalCode" : "48124" }
}
}]'
My problem is that I do not know how to add the -d to the curl resource that appears in the first case just after the URL
This works for me:
$url = "https://connect.apisite.com/api/v1/users";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
$request_headers = array();
$request_headers[] = 'authToken: ' . $authResponse;
$request_headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
I tried just appending the -d to the URL as
$url = "https://connect.apisite.com/api/v1/users -d";
That did not work.
My guess is there is a constant I need to use like
curl_setop($ch, CURLOPT_XXXXX, '-d');
but I do not know what CURLOPT_XXXX should be.
Any help would be appreciated.
I'm not sure why you use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); as your call structure seems could be done by a regular POST call which could be handled by:
curl_setopt(CURLOPT_POST, true);
which in turn will call the -d flag of cURL as per PHP document:
CURLOPT_POST: TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
Also, you need to change curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); because doing this will make cURL to pass the data as multipart/form-data. Instead, structure your data as a URL-encoded string, something like
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postData)));
(note: I haven't tested the latter line above but you can test it and adjust as per your requirements), as per PHP documentation note:
Note:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
Thanks everyone for your help and suggestions.
As was mentioned I did not need to do anything to add the -d
I got the response I need using the following for postData
$postData = json_encode(array(array('emailAddress' => $emailObj, 'firstName' => $firstName, 'lastName' => $lastName)));
or
$postData = json_encode(array(array('emailAddress' => $emailObj, 'firstName' => $firstName, 'lastName' => $lastName, 'homePostalAddress' => $homePostalObj)));
In both request the method is POST, as the previous answer you can set CURLOPT_POST option. I see the only different is about the data you are sending, in one without zipCode and another with. So, you can just prepare the data before including the zipCode or not in your array of data. You can try something like below.
$dataRequest = [
'firstName' => "John",
'lastName' => "Smith",
'emailAddress' => [
'address' => 'johnsmith#test.com'
],
'homeAddress' => [ //dont send this key in the case you dont want zipCode in the request.
'postalCode'=> '48124'
],
];
$url = "https://connect.apisite.com/api/v1/users";
$authToken = '12345';
$ch = curl_init();
/**
the idea with urldecode is because some api does not accept the
encoded urls in your case is not important due your data does not
contains any url but if tomorrow you want to include smth like
'customerUrl'=>'https://myhomepage.com' the result of http_build_query
will be like 'https%3A%2F%2Fmyhomepage.com'
*/
$data = urldecode(http_build_query($dataRequest));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{$authToken}:");
$headers = [];
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (!curl_errno($ch)) {
/**
HANDLE RESPONSE, CHECK FOR PROPER HTTP CODE DEPENDING OF THE API RESPONSE,
IN YOUR CASE I GUESS IS CREATE USER YOUR GOAL, SO MAYBE RESPONSE IS 'HTTP_CREATED'
BUT IF THIS FUNCTION WILL BE GENERIC BETTER SWITCH LIKE THIS:
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case Response::HTTP_OK:
case Response::HTTP_CREATED:
case Response::HTTP_ACCEPTED:
$response = json_decode($response, true);
break;
default:
$response = [];
}
*/
}
curl_close($ch);
return $response;
This example is with content-type not in json format, you can change it if is requirement of api.
I have used curl in php and set parameter in "CURLOPT_POSTFIELDS". And I use return $_REQUEST/$_POST on the target url for checking my passed parameter are posted correctly. But I am not able to check the posted parameter in target page.
Example of target url:- http://www.eg.com/target
curl_setopt($ipnexec, CURLOPT_URL, "http://www.eg.com/target");
CODE
$clientId = "AXLAatA9ucEkGt2C9y5SuNRd24Ys4NPod8VJmNNFq5otso1RQRIn";
$secret = "EGOojWJihcU8wnGTVQivKOsD_ylB5mMdaWmbn_1UWGlqbaugSCOZ";
$post = array(
"key" => $clientId,
"secret" => $secret
);
$ipnexec = curl_init();
curl_setopt($ipnexec, CURLOPT_URL, "http://www.eg.com/target");
curl_setopt($ipnexec, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ipnexec, CURLOPT_POST, true);
curl_setopt($ipnexec, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ipnexec, CURLOPT_RETURNTRANSFER, true);
$ipnresult = curl_exec($ipnexec);
$result = json_decode($ipnresult);
Any helps !!
Regards
Patrick
If you do have access to the endpoint at http://www.eg.com/target, you need to change the stream used. $_REQUEST is for form encoded data only. To access raw json, you need to use
$data = file_get_contents('php://input');
And then if you want to "overwrite $_POST, use
$_POST = json_decode($data, true);
This is an answer to the question when using Mailgun's class. I'm seeking to find an answer that applies to using CURL inside of PHP.
Using PHPMailer's class, I can send multiple attachments in the following manner:
$mail->AddStringAttachment($attachment1, $title1);
$mail->AddStringAttachment($attachment2, $title2);
Because I am not fetching a file from the server, and am instead composing in a string, I need to specify the title for each enclosure.
Now, I'd like to accomplish that using Mailgun via PHP and CURL. So far, I am utilizing the following technique for sending mail without attachments:
$api_key="[my api key]";
$domain ="[my domain]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:'.$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.$domain.'/messages');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"from" => "[sender]",
"to" => $to,
"subject" => $subject,
"html" => $content
));
Following this same convention of specifying the fields in an array, what's the equivalent of sending string attachments and specifying the titles using PHP and CURL with Mailgun?
I gave up on using string attachments and instead created two temporary files (based on content previously composed by another function) inside of a temporary directory (with the directory name based on the user's unique ID). (Thanks to drew010 for starting me down the correct path.)
I doubt the following function will be useful to others as is, but perhaps various portions will be helpful to others desiring similar functionality.
function sendFormattedEmail ($coverNote, $attachment1, $title1, $attachment2, $title2) {
global $userID, $account;
if (!file_exists("temp_{$userID}")) {
mkdir("temp_{$userID}");
}
file_put_contents("temp_{$userID}/{$title1}", $attachment1);
file_put_contents("temp_{$userID}/{$title2}", $attachment2);
$api_key="[api_key]";
$domain ="[my_domain]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:'.$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.$domain.'/messages');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"from" => "[my_return_address]",
"to" => $account,
"subject" => "your requested files",
"text" => $coverNote,
"attachment[1]" => new CurlFile("temp_{$userID}/{$title1}"),
"attachment[2]" => new CurlFile("temp_{$userID}/{$title2})"
));
$response = curl_exec($ch);
$response = strtolower(str_replace("\n", "", trim($response)));
$result= json_decode($response, true);
$status = explode(".", $result["message"]);
if ($status[0] == "queued") {
echo json_encode(array ("result" => "success"));
}
else {
echo json_encode(array ("result" => "failure"));
}
curl_close($ch);
unlink ("temp_{$userID}/{$title1}");
unlink ("temp_{$userID}/{$title2}");
rmdir ("temp_{$userID}");
}
As shown above, the function strips the newline characters from Mailgun's response in order to enable the use of json_encode. The trim and lowercase conversion are just my preference.
After reporting the result back to the calling function, it removes the two temporary files and then the temporary directory.
This code return null value. Value is: {}
I checked it, CURL is enabled but still it returns null -> {}. Do you get the results?
Please help me asap.
PHP code is blow:
$urlstring="http://www.google.com/loc/json";
$ch=curl_init($urlstring);
$cell_towers = array();
$row=new stdClass();
$row->location_area_code=3311;
$row->mobile_network_code=71;
$row->cell_id=32751;
$row->mobile_country_code=404;
$cell_towers[]=$row;
$param = array(
'host'=> 'localhost',
'version' => '1.1.0',
'request_address' => true,
'cell_towers' => $cell_towers
);
$param_json=json_encode($param);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$param_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$result=curl_exec($ch);
echo $result;
Try replacing the new stdClass() with a simple array().
Also did you try to echo $param_json? Is the data properly formatted?
Finally, I'm surprised the POSTFIELDS is the whole JSON data. Are you sure it shouldn't be something like curl_setopt($ch,CURLOPT_POSTFIELDS, array("data" => $param_json))?