Upload file using Curl and receive them in Laravel method - php

I have been trying to upload file to using curl using laravel app end point.
Below code is on separate server.
$header = $this->getCurlHeader();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$cfile = new \CURLFile($this->filePath . $this->csvFile, 'text/csv','text.csv');
//print_r($cfile);exit;
$postData = array('csv' => $cfile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$response = curl_exec($ch);
$hhtpCode = curl_getinfo($ch);
curl_close($ch);
//$this->dbg($hhtpCode);
$this->dbg(json_decode($response,1),1);
And receiving end in laravel app hosted on different server.
public function insert(Request $request, $feed=''){
//return response()->json(var_dump($request->all()));
//return response()->json("here in insert");
return response()->json($_FILES);
echo "here";
dd($_FILES);
}
It returns me empty response.
I am able to verify curl request using headers.
Any suggestion will be helpful.
Thanks.

You can try something like this on the source server instead:
$target_url = 'https://mywebsite.com'; // Write your URL here
$dir = '/var/www/html/storage/test.zip'; // full directory of the file
$cFile = curl_file_create($dir);
$post = array('file'=> $cFile); // Parameter to be sent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=json_decode(curl_exec($ch));
curl_close ($ch);
From the destination server, print the request sent.
public function insert(Request $request){
dd($request->file);
}

please use curlfile method to upload files.
if(isset($_FILES) && !empty($_FILES['identity_doc']))
{
foreach($_FILES['identity_doc'] as $key => $file)
{
$data['document'.$i]= new CURLFile($_FILES['identity_doc']['tmp_name'][$i], $_FILES['identity_doc']['type'][$i],$_FILES['identity_doc']['name'][$i]);
}
}

if(isset($_POST['submit']))
{
$fileName=$_FILES['resume']['name'];
$type=$_FILES['resume']['type'];
$tempPathname=$_FILES['resume']['tmp_name'];
$handle = fopen($tempPathname, "r");
$POST_DATA = fread($handle, filesize($tempPathname));
$url="https://objectstorage.region-name.oraclecloud.com/p/par-id/n/namespace`enter code here`/b/bucket-name/o/images/".$fileName;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS=>$POST_DATA ,
CURLOPT_HTTPHEADER => array(
'Content-Type: '.$type,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($response) {
echo 'error';
} else {
echo $url;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="resume">
<button type="submit" name="submit">submit</button>
</form>

Related

How to add contact in list using (Send Grid) php api

I am trying to add contact in list using php api but its throwing bellow snippet error
string(51) "{"errors":[{"message":"request body is invalid"}]} " {"email":"hello#test.com","first_name":"hh","last_name":"User"}
I am using bellow snippet code:
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists/12345/recipients'; //12345 is list_id
$params = array(
'email' => 'hello#test.com',
'first_name' => 'hh',
'last_name' => 'User'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.XXXXXXXX");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
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;
Can any one tell me how to resolve this issue.
You should inspect the request that you are sending and compare the JSON in the body to a valid request to really see what's happening. The output of your json_encode here will be an array, but the API expects an object. Your request body needs to be
[{"email":"hello#test.com","first_name":"hh","last_name":"User"}]
And what you are doing right now is sending
{"email":"hello#test.com","first_name":"hh","last_name":"User"}
You can fix this several ways. You could use your favorite string manipulation functions to append the brackets, or you could skip the encoding and send the JSON as a string (since you're specifying the content type).
After looking at sendgrid API and then testing on my own server I was able to add contacts to the contact list. As you already created a list next step is to create recipients to be added to the list. You can do this way
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/recipients'; //12345 is list_id
$params = array(array(
'email' => 'amitkray#gmail.com',
'first_name' => 'Amit',
'last_name' => 'Kumar'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
curl_close($ch);
}
var_dump($data);
?>
After creating recipients you can now add them to list. You will get an id like this YW1pdGtyYXlAZ21haWwuY29t which is base64 encode of your email id.
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients/YW1pdGtyYXlAZ21haWwuY29t'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.00000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
After adding that you can verify if user has been added to list
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients?page_size=100&page=1'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
Note: best way is to create a class as most of the codes are being repeated. I will make a wrapper class for sendgrid and post it here soon with ability to do all task that is possible through sendgrid API.
First think is you will need to insert your email to send grid recipients:
<?php
$curl = curl_init();
$email = "example#mail.com";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/recipients",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "[{\"email\": \".$email.\"}]",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.0000000",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
$a = json_decode($response);
$b = $a->persisted_recipients; //get id of email
$r_id = $b[0]; // store it
}
?>
after that insert it in list by doing this way.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/lists/123456/recipients/$r_id",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "null",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.0000000000",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
for more info visit:https://sendgrid.com/docs/API_Reference/api_v3.html

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');

curl post multipart/form-data api

I can not send pictures.
More information - Telegram
https://core.telegram.org/bots/api#sendphoto
I want to send a picture, this method is useless.
Are there any other method?
<?php
$Photo = "http://www.pawprint.net/images/news/1-4fac83467069c.png";
$IDUser = 26034352;
$Data = array(
'chat_id' => $IDUser,
'photo' => $Photo,
'caption' => 'hi'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.telegram.org/bot93816942:AAHnjqsjpJjRItc7ySbUq4C5IRLqytpPK6k/sendPhoto");
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$options);
// in real life you should use something like:
curl_setopt($ch, CURLOPT_POSTFIELDS,
http_build_query($Data));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// frther processing ....
if ($server_output == "OK") {
echo "ok";
}
?>
I see you want to send a picture located on a external server with its URL
so you can do as follow
define('website', 'https://api.telegram.org/bot<bot-token>');
function send($method, $datas)
{
$url = website . "/" . $method;
if (!$curld = curl_init()) {
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $datas);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close($curld);
}
now just call this function with proper method name and data. example for sending a photo:
$postfields = array(
'chat_id' => $ChatID,
'photo' => "http://url.of/photo.jpg"
);
send("sendPhoto", $postfields);

How to get response using cURL in PHP

I want to have a standalone PHP class where I want to have a function which calls an API through cURL and gets the response. Can someone help me in this?
Thanks.
Just use the below piece of code to get the response from restful web service url, I use social mention url.
$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
The crux of the solution is setting
CURLOPT_RETURNTRANSFER => true
then
$response = curl_exec($ch);
CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
If anyone else comes across this, I'm adding another answer to provide the response code or other information that might be needed in the "response".
http://php.net/manual/en/function.curl-getinfo.php
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($errors);
var_dump($response);
Output:
string(0) ""
int(200)
// change www.google.com to www.googlebofus.co
string(42) "Could not resolve host: www.googlebofus.co"
int(0)
The ultimate curl php function:
function getURL($url,$fields=null,$method=null,$file=null){
// author = Ighor Toth <igtoth#gmail.com>
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please crete 'cookies' dir to store local cookies if neeeded
// do not modify below
$useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
$timeout= 240;
$dir = dirname(__FILE__);
$_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
$timeout= 3600;
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
return $content;
}
curl_close($ch);
}
am using this simple one
ยดยดยดยด
class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);

Passing $_POST values with cURL

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.

Categories