Passing $_POST values with cURL - php

How do you pass $_POST values to a page using cURL?

Should work fine.
$data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an # (for <input type="file"> fields)
$data['file'] = '#/home/user/world.jpg';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.
It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.
$data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
I hope this will help others save their time.
See:
curl_init
curl_setopt

Ross has the right idea for POSTing the usual parameter/value format to a url.
I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);
curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);
$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set CURLOPT_RETURNTRANSFER or CURLOPT_HEADER.

Another simple PHP example of using cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Instead of using curl_setopt you can use curl_setopt_array.
http://php.net/manual/en/function.curl-setopt-array.php

$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);

$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);

<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If any HTTP authentication is needed.
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This is a sample array. You can use $arrPostData = $_POST
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your post data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // Only USE this when request JSON data.
$mixResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // Only USE this when requesting JSON data
),
// If HTTP authentication is required, use the below lines.
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));
// $mixResponse contains your server response.

Related

Stability.ai API returning error: cannot unmarshal object into Go struct field TextToImageRequestBody.text_prompts of type

I'm trying to use the Stability.ai API to generate Stable Diffusion AI images.
I got my API key from https://beta.dreamstudio.ai/membership?tab=apiKeys
I am following the textToImage docs here: https://api.stability.ai/docs#tag/v1alphageneration/operation/v1alpha/generation#textToImage
I'm trying to use PHP / cURL to generate an Image using the API
$url = 'https://api.stability.ai/v1alpha/generation/stable-diffusion-512-v2-0/text-to-image';
$data = array(
"api_key_header_Authorization" => "sk-XXX"); // API key here
$data['text_prompts']['text'] = 'a happy robot';
$data['text_prompts']['weight'] = 1;
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
Here is the response:
{"name":"decode_payload","id":"sDzSQ7y2","message":"json: cannot unmarshal object into Go struct field TextToImageRequestBody.text_prompts of type []*server.TextPromptRequestBody","temporary":false,"timeout":false,"fault":false}
I was hoping to get a success response.
text_prompts must be an array of objects.
$data['text_prompts'][0]['text'] = 'a happy robot';
$data['text_prompts'][0]['weight'] = 1;
See here:
https://api.stability.ai/docs#tag/v1alphageneration/operation/v1alpha/generation#textToImage (The Box on the right side)
As Foobar mentioned, I needed an array of objects.
Now I have:
$url = 'https://api.stability.ai/v1alpha/generation/stable-diffusion-512-v2-0/text-to-image';
$headers = [
'Authorization: sk-XXX', // API key
'Accept: image/png',
];
$data['text_prompts'] = $arr_of_obj = array(
(object) [
'text' => 'a happy robot',
'weight' => 1
]);
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
which returns the png data of generated AI image

Openfigi php request -> Request body must be a JSON array

I am trying to use the openfigi api with php. I keep getting this error message: "Request body must be a JSON array.". Any ideas on how to solve this? I have tried several solutions.
$curlUrl = 'https://api.openfigi.com/v2/mapping';
$data = array('idType' => 'ID_WERTPAPIER', 'idValue' => '851399', 'exchCode' => 'US');
$j = json_encode($data);
//$apiToken = 'X-OPENFIGI-APIKEY: xxx';
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Content-Type: application/json';
//$httpHeadersArray[] = $apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);
$res = curl_exec($ch);
echo "<pre>";
print_r($res);
echo "</pre>";
had the same problem, but solved it.
This is my working code:
// The url you wish to send the POST request to
$url = 'https://api.openfigi.com/v2/mapping/';
// Create a new cURL resource
$ch = curl_init($url);
// The data to send to the API
$postData = array(
array(
"idType" => "ID_ISIN",
"idValue" => "US4592001014"
)
);
// Setup cURL
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
print_r(json_encode($postData));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
print_r($responseData);

PHP cURL: how to set body to binary data?

I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?
The command line equivalent of what I'm trying to achieve is:
curl --request POST --data-binary "#myimage.jpg" https://myapiurl
You can just set your body in CURLOPT_POSTFIELDS.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Taken from here
Of course, set your own header type, and just do file_get_contents('/path/to/file') for body.
This can be done through CURLFile instance:
$uploadFilePath = __DIR__ . '/resource/file.txt';
if (!file_exists($uploadFilePath)) {
throw new Exception('File not found: ' . $uploadFilePath);
}
$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
See - https://github.com/andriichuk/php-curl-cookbook#upload-file
to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
credits: How to POST a large amount of data within PHP curl without memory overhead?
Try this:
$postfields = array(
'upload_file' => '#'.$tmpFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
Below solution worked fine for me.
$ch = curl_init();
$post_url = "https://api_url/"
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$post = array(
'file' => '#' .realpath('PATH_TO_DOWNLOADED_ZIP_FILE')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
refered: curl to php-curl
You need to provide appropriate header to send a POST with the binary data.
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file);
Your $arr_containing_file can for example contain file as expected (I mean, you need to provide appropriate expected field by the API service).
$arr_containing_file = array('datafile' => '#inputfile.ext');

How to parse json output?

I tried to parse this url
https://esewa.com.np/epay/transdetails?pid=AddFund-C-11970239- 9625960&amt=100&scd=nprhosting&rid=00C3LF0
{
"code":"00",
"msg":"Success",
"txnDetail": {
"txnCode":"00C3LF0",
"amt":"100.0",
"date":"2015-07-16 23:44:18.0",
"payerId":"dipsnwc#gmail.com",
"status":"COMPLETE",
"pid":"AddFund-C-11970239-9625960",
"txAmt":"0",
"psc":"0",
"pdc":"0"
}
}
Like this
$fields = array(
'pid' => "AddFund-C-11970239-9625960";
'amt' => "100.0";
'scd' => "nprhosting";
'rid' => "00C3LF0";
);
$field2 = json_encode($fields);
$url = "https://esewa.com.np/epay/transdetails";
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $field2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($field2))
);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
//
///Deocde Json
$data = (json_decode($result, true));
var_dump($data);
$message =$data['msg'];
$status =$data['txnDetail']['status'];
echo $message;
echo $status;
Still no output ??
I tried it and worked..
$url = 'https://example.com/epay/transdetails?pid=AddFund-C-11970239-9625960&amt=100&scd=nprsite&rid=00C3LF0';
$data = file_get_contents($url);
$arr = json_decode($data,true);
echo $arr['txnDetail']['status'];
print_r($arr);
Array is incorrect, remove ::
$fields = array(
'pid' => "AddFund-C-11970239-9625960",
'amt' => "100.0",
'scd' => "nprhosting",
'rid' => "00C3LF0"
);
and try
$url = "http://examplesite.com/epay/transdetails?" . http_build_query($fields);
Chuck the POSTFIELDS and HTTPHEADER
curl_setopt($ch, CURLOPT_POST, false);
The parameters are expected to be as GET(as per the link you have provided), keep it simple.
Also check this answer for better understanding on how to send HTTP GET request with PHP CURL.

Curl POST attachment

I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);

Categories