How to get response using cURL in PHP - 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);

Related

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

Upload file using Curl and receive them in Laravel method

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>

Setting cookies for user/browser after a CURL post request [duplicate]

I have some problem with PHP Curl and cookies authentication.
I have a file Connector.php which authenticates users on another server and returns the cookie of the current user.
The Problem is that I want to authenticate thousands of users with curl but it authenticates and saves COOKIES only for one user at a time.
The code for connector.php is this:
<?php
if(!count($_REQUEST)) {
die("No Access!");
}
//Core Url For Services
define ('ServiceCore', 'http://example.com/core/');
//Which Internal Service Should Be Called
$path = $_GET['service'];
//Service To Be Queried
$url = ServiceCore.$path;
//Open the Curl session
$session = curl_init($url);
// If it's a GET, put the GET data in the body
if ($_GET['service']) {
//Iterate Over GET Vars
$postvars = '';
foreach($_GET as $key=>$val) {
if($key!='service') {
$postvars.="$key=$val&";
}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
//Create And Save Cookies
$tmpfname = dirname(__FILE__).'/cookie.txt';
curl_setopt($session, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($session, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
// EXECUTE
$json = curl_exec($session);
echo $json;
curl_close($session);
?>
Here is the process of authentication:
User enters username and password: Connector.php?service=logon&user_name=user32&user_pass=123
Connector.php?service=logosessionInfo returns info about the user based on the cookies saved earlier with logon service.
The problem is that this code saves the cookie in one file for each user and can't handle multiple user authentications.
You can specify the cookie file with a curl opt. You could use a unique file for each user.
curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );
The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.
function fetch( $url, $z=null ) {
$ch = curl_init();
$useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );
if( isset($z['post']) ) curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
if( isset($z['refer']) ) curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );
curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $z['cookiefile'] );
curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );
$result = curl_exec( $ch );
curl_close( $ch );
return $result;
}
I use this for quick grabs. It takes the url and an array of options.
In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Certificates
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
First create temporary cookie using tempnam() function:
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
Then execute curl init witch saves the cookie as a temporary file:
$ch = curl_init ("http://uri.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
Or visit a page using the cookie stored in the temporary file:
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
This will initialize the cookie for the page:
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .
You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:
function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
$result = false;
if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
{
if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
{
curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
}
else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
{
if (is_array($data) === true)
{
foreach (preg_grep('~^#~', $data) as $key => $value)
{
$data[$key] = sprintf('#%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '#'))), '/') . (is_dir(ltrim($value, '#')) ? '/' : ''));
}
if (count($data) != count($data, COUNT_RECURSIVE))
{
$data = http_build_query($data, '', '&');
}
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (isset($cookie) === true)
{
curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
}
if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
{
curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
}
if (is_array($options) === true)
{
curl_setopt_array($curl, $options);
}
for ($i = 1; $i <= $retries; ++$i)
{
$result = curl_exec($curl);
if (($i == $retries) || ($result !== false))
{
break;
}
usleep(pow(2, $i - 2) * 1000000);
}
}
curl_close($curl);
}
return $result;
}
And pass this as $cookie parameter:
$cookie_jar = tempnam('/tmp','cookie');
You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.
Solutions which are described above, even with unique CookieFile names, can cause a lot of problems on scale.
We had to serve a lot of authentications with this solution and our server went down because of high file read write actions.
The solution for this was to use Apache Reverse Proxy and omit CURL requests at all.
Details how to use Proxy on Apache can be found here:
https://httpd.apache.org/docs/2.4/howto/reverse_proxy.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');

Equivalent of file_get_contents() with CURL?

I'm trying to get some JSON data from a url like this:
$url = 'http://site.com/search.php?term=search term here';
$result = json_decode ( file_get_contents($url) );
However the client's webhost has got the allow_url_fopen setting disabled, hence the code above doesn't work.
What's the equivalent code of the lines above? Basically, a search term needs to be submitted via $_GETto the url.
Like this:
$url = 'http://site.com/search.php?term=search term here';
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, $url);
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$aData = curl_exec($rCURL);
curl_close($rCURL);
$result = json_decode ( $aData );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonData = curl_exec($ch);
if ($jsonData === false) {
throw new Exception('Can not download URL');
}
curl_close($ch);
$result = json_decode($jsonData);
All you need is here.
http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl
Basically, try something like this
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_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = json_decode($content);
return $header;
}
have you checked it out like this.?
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Thanks.
// create a new cURL resource
$ch = curl_init();
// set parameters
$parameters = array(
'foo'=>'bar',
'herp'=>'derp'
);
// add get to url
$url = 'http://example.com/index.php'
$url.= '?'.http_build_query($parameters, null, '&');
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return the content
// execute
$data = curl_exec($ch);
You should then have the file contents in $data, you'll probably want to do some error checking but you can find out how to do that at php.net.

Categories