CURL_RETURNTRANSFER downloding large files - php

I use a funtion to download files trough a private API.
Everything goes fine to download small/medium files, but large files is impossible beacause it uses too much memory.
Here is my function:
protected function executeFile($method, $url, $params=array(), $as_user=null) {
$data_string = json_encode($params);
$method = strtoupper($method);
$ch = curl_init();
if($method == 'GET') {
$url = $this->options['api_url'].$url.'?';
$url .= $this->format_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($as_user) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Token: '.$this->token,
'As: '.$as_user
));
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Token: '.$this->token
));
}
$result_json = curl_exec($ch);
$curl_info = curl_getinfo($ch);
$return = array();
$return["result"] = $result_json;
$return["entete"] = $curl_info;
return $return;
}
How could i optimize this to download files to disk instead of memory ?
Thanks

use CURLOPT_FILE . It will ask for file pointer where download will be saved.
code will be like
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$fp = fopen("your_file", 'w+');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);

You can use CURLOPT_FILE, like this:
protected function executeFile($method, $url, $params=array(), $as_user=null) {
$data_string = json_encode($params);
$method = strtoupper($method);
$fp = fopen ('savefilepath', 'w+');
$ch = curl_init();
if($method == 'GET') {
$url = $this->options['api_url'].$url.'?';
$url .= $this->format_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
....
curl_exec($ch);
fclose($fp);
.....
return $return;
}

Related

curl request to localhost takes a huge amount of time

I need to make curl request via PHP to the same local virtualhost url. Its really simple. If I make it via Postman or in command line it takes miliseconds. But as I run it in PHP it is still loading without response. I make a log to file after each step so I can say the code stops after Debugger::log(5555555555555).
This is the code:
public function sendRequest(string $url, array $data = null, $method = 'GET')
{
$url = $this->apiUrl . $url;
$ch = curl_init($url);
$json = json_encode($data);
Debugger::log(2222222222222);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
Debugger::log(2222222222222);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
if ($method == 'POST' or $method == 'PUT') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
Debugger::log(33333333333);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_PORT , 80);
Debugger::log(44444444444);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiKey,
//'X-API-Token: v4yWSYY2Od7-iA6Vi3e8fRNWMkvii-eF',
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
Debugger::log(5555555555555);
$output = curl_exec($ch);
Debugger::log(6666666666666);
if( curl_errno($ch) ) {
Debugger::log(curl_error($ch), Debugger::EXCEPTION);
throw new \Exception( curl_error($ch) );
}
Debugger::log(77777777777777);
$header = curl_getinfo($ch);
Debugger::log(88888888888888);
curl_close($ch);
$return = array("header" => $header, "output" => $output);
return $return;
}

CURLOPT_URL how to get two different links?

The below code works with API URL: https://api2.example.com/service/vps/list
but the API provider has changed, they use 2 URLs at the same time, for example: https://api2.example.com/service/vps/list and https://api2.example.com/service/dedicated/list
how to get vps and dedicated information from the above two links?
this is my code working with https://api2.example.com/service/vps/list only:
if (!defined("WHMCS"))
die("This file cannot be accessed directly");
use Illuminate\Database\Capsule\Manager as Capsule;
class FKL
{
public $apikey = '';
public $apiurl = 'https://api2.example.com/';
public function __construct($apikey = '')
{
$this->apikey = $apikey;
}
public function getList()
{
$sendparams = [];
$sendparams['APIKey'] = $this->apikey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiurl . "service/vps/list");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sendparams, JSON_PRETTY_PRINT));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$list = json_decode($result, true);
return $list['data'];
}
}
public function getOSList()
{
$sendparams = [];
$sendparams['APIKey'] = $this->apikey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiurl . "service/vps/os");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sendparams, JSON_PRETTY_PRINT));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$list = json_decode($result, true);
return $list['data'];
}
}
......
Thank you!
I have added code:
curl_setopt($ch, CURLOPT_URL, $this->apiurl . "service/dedicated/list");
bellow:
curl_setopt($ch, CURLOPT_URL, $this->apiurl . "service/vps/list");
and now are working!

Zoho API-V2 Add Attactmetn URL

I am trying to add attachment url in crm. I am flowing this documentation . But i got error !
This is my code :
$zoho_url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$post['attachmentUrl'] = $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_URL,$zoho_url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$headers = array();
$headers[] = "Authorization: ".$authtoken;
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_errno($ch);
curl_close ($ch);
if ($err) {
$result = $err;
} else {
$result = $response;
}
print_r($result);
This is response :
{"code":"INVALID_REQUEST","details":{},"message":"unable to process your request. please verify whether you have entered proper method name, parameter and parameter values.","status":"error"}
I made this code for attach a file in a zoho record.
//Get the oauth Token
$accessToken=getCurrentAccessToken();
// files to upload
$tmpfile;
$filename;
$type;
foreach($files as $file){
$tmpfile = $file['tmp_name'];
$filename = basename($file['name']);
$type = $file['type'];
}
$cfile = new CURLFile(realpath($tmpfile),$type,$filename);
$post_data = array (
'file' => $cfile
);
$url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$headers = array(
'Content-Type: multipart/form-data',
sprintf('Authorization: Zoho-oauthtoken %s', $accessToken)
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
return $response;

Php Curl Sequential function

Is this possible? We want to achieve this sequence of functions to integrate.I'm kinda new at php curl functions. The first line of code is what we want to achieve.
Here's our php:
<?php
paythrougPaypalSanbox() -> publishSite() -> redirectToCurrentSite()
header("Location:".$dashboard_link);
function paythrougPaypalSanbox() {
$data = $_GET['siteName'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.sandbox.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
so on...
curl_close($ch);
}
function publishSite() {
$data = $_GET['siteName'];
curl_setopt($ch, CURLOPT_URL, 'https://api.dudamobile.com/api/sites/multiscreen/publish/'.$siteName);
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
so on..
curl_close($ch);
}
function redirectToCurrentSite() {
$data = $_GET['siteName'];
curl_setopt($ch, CURLOPT_URL, 'http://trilogy.editor.multiscreensite.com/home/site/'.$siteName);
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
so on..
}
curl_close($ch);
return $dashboard_link;
}
?>
function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
return false;
}
curl_close($ch);
return $data;
}
if(curl($url)){
// second request
}

How do you Upload Image to parse.com usint REST API + PHP?

Currently using this, but file that is stored is empty, so I supose no data is going through.
$post = array("file"=>'#'.$_FILES['uploadfile']['tmp_name']);
$ch = curl_init();
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id : XXXXXXXXXXXXXX','X-Parse-REST-API-Key: XXXXXXXXx', 'Content-type: image/jpeg'));
curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/files/'.$_FILES['uploadfile']['name']);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
Got it working. You need to send the binary data as the post field. duh.
Before this you should probably create some restrictions (file size, type etc)
$post = file_get_contents($_FILES['uploadfile']['tmp_name']);
$ch = curl_init();
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id : XXXXXXXX','X-Parse-REST-API-Key: XXXXXXXXXXXXXXX', 'Content-type: image/jpeg'));
curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/files/'.$_FILES['uploadfile']['name']);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
Use this work perfectly same way as we need.....
function sendImageToParse($url, $filename) {
$this->layout = FALSE;
$this->autoRender = false;
$headers = array(
'X-Parse-Application-Id:' . $this->APPLICATION_ID,
'X-Parse-REST-API-Key:' . $this->REST_API_KEY,
'Content-Type: image/jpeg'
);
$data = file_get_contents($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/files/' . $filename);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function add() {
if ($this->request->is('post')) {
$giftUniqueId = time();
$urlFileImage = $allData['Coupon']['imageLink'];
//Eg : "http://localhost/favrapp/img/couponsLogo/gap.jpg";
$filename = $allData['Coupon']['imageName']; //Eg : "gap.jpg";
$responseFile = $this->sendImageToParse($urlFileImage, $filename);
$arrayInt = json_decode($responseFile);
if (!empty($arrayInt)) {
$name = $arrayInt->name;
$url = $arrayInt->url;
} else {
$name = '';
$url = '';
}
//Save to table by creating object
$url = 'https://api.parse.com/1/classes/giftcard';
$data = array('name' => $allData['Coupon']['name'],
'couponType' => $allData['Coupon']['coupontype'],
'giftcardTypeid' => $allData['Coupon']['giftcardTypeid'], 'giftcardcheckid' => $giftUniqueId,
'logo' => array('name' => $name, '__type' => 'File', 'url' => $url),
);
$_data = json_encode($data);
$headers = array(
'X-Parse-Application-Id: ' . $this->APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $this->REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_exec($curl);
curl_close($curl);
}
}

Categories