How to download a .gz file using curl? - php

So I have written an Ajax call to download a file after clicking on download button so when I hit the API that I was using to get a file over CURL call which returns the file resource stream so if its a pdf then its fine i am using fopen and fwrite to write the data into a file and its working but when i try to get .gz file stream its not working i mean the .gz file is created but its nothing in that file also when i try to extract it gives me error i am using ubuntu 18.04 and Codeigniter 3
private function __curl(
$url,
$request = "POST",
$data = [],
$header = ["Content-Type: application/json"]
) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $this->apiUrl . $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $request,
CURLOPT_POSTFIELDS => !empty($data) ? json_encode($data) : "",
CURLOPT_HTTPHEADER => $header,
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return $err;
} else {
$path = "path/to/file/".$fileName;
$fp = fopen($path, 'w');
fwrite($fp, $response);
fclose($fp);
}
}
so I am using this function to call the api and i get the .gz file as a response stream and I want to convert that stream to a as it .gz file with data in it and save it in given path.

You can download a .gz file using curl in php by using the following code:
<?php
// Initialize cURL session
$ch = curl_init();
// Set the URL of the file to be downloaded
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.gz');
// Set cURL to return the contents of the file as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute cURL session and store the contents of the file into a variable
$data = curl_exec($ch);
// Close cURL session
curl_close($ch);
// Write data to local file
$fp = fopen('file.gz', 'w');
fwrite($fp, $data);
// Close local file handle
fclose($fp); ?>

Related

PHP cURL not working for localhost with remote server relation

I'm currently working on copying a file from localhost to a remote server using PHP cURL.
I have two separate files, one for the localhost which sends the file, and another for the remote server to receive the file and save it to the server. The codes are as follows :
send.php
<?PHP
$web_page_to_send = "http://admin123.unaux.com/receive.php";
$file_name_with_full_path = "test.jpg";
$post_request = array
(
"sender" => "tmp",
"file" => curl_file_create($file_name_with_full_path)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $web_page_to_send);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_request);
$result = curl_exec($ch);
curl_close($ch);
echo "<br>Result: ".$result;
?>
receive.php
<?PHP
if(isset($_POST['sender']))
{
echo "got it !";
$file_name = "tmp/".$_POST['sender']."-".$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $file_name);
echo "Successful Attempt! <br><br>Filename: ".$file_name;
echo '<br><br> <img src="'.$file_name.'" width="300px"></img>';
}
else
{
echo 'Unauthorized Access!';
}
?>
The codes are working fine on localhost, but after placing the receive.php to the remote server, the file is no more sent and displayed. "http://admin123.unaux.com/receive.php" is where the file is on the remote server. I'm using profreehost free server as the remote server.
Remote server folder structure : Remote Server File and Folder Structure
Can anyone please help me with this problem?
Thank you.
Please get all received data in the receive.php file as below:
$post_data = trim(file_get_contents("php://input"));
after this, try to print $post_data. If you will get null value then response is not hitting at your file.
Try to send above data with below code:
$web_page_to_send = "http://admin123.unaux.com/receive.php";
$file_name_with_full_path = "test.jpg"; // Please write here full file path in the system
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $web_page_to_send,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 20,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('sender' => 'tmp','file'=>new CURLFILE($file_name_with_full_path)),
CURLOPT_HTTPHEADER => array(
"Content-Type: image/jpg"
),
CURLOPT_UPLOAD=>true,
));
$response = curl_exec($curl);
$http_response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

How to turn API response into an image?

I'm trying to work with an API using Postman. In Postman the image displays fine. I am using Postman to generate the following code
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.com/v2/tier1/XXXXX/photos/photo/MYPHOTOIDISHERE/download?api_key=MYAPIKEYISHERE",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 74f19da6-d4ba-fe02-4ad3-2a313b472ca2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only modification I have made to the code from Postman is the CURLOPT_SSL_VERIFYPEER as I was getting an error.
The image displays perfectly in Postman but when I try to use the code myself I get a long string that looks like UTF. A small sample (it's very long) of this is as follows;
����JFIF``��C #!!!$'$ & ! ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
How do I convert this into an image?
The result you are seeing is the actual bytes of the image.
You need to save that to a file or process it as image bytes. To save it, dump it to a file using file_put_contents($filename, $data)
// Instead of 'echo $response';
file_put_contents('image.jpg', $response);
You will see a new file image.jpg in your script's directory.
This assumes the image is a jpeg, you could do some checks to determine the type before saving it.
I am able to save image in folder, but problem is that Its showing error - window photo viewer can't open this picture because the file appears to be damaged, corrupted or is too large
here is my code
$oAuthToken = $token->access_token;
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $googlefileid . '?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
$authHeader ,
]);
$data = curl_exec($ch);
curl_close($ch);
Storage::put($googlfilename,$data);
Please tell me what i am doing wrong.

Upload File Via PHP Curl PUT

Having quite a bit of trouble PUT-ting a PDF. I've managed to get it working fine in Postman, using the code below (large code block) and appending the PDF via the body as form-data. I'm trying to replicate this in PHP now. I'm having trouble attaching the PDF though.
I've tried numerous techniques trying to attach the PDF via "CURLOPT_INFILE", "CURLOPT_POSTFIELDS" to no avail.
I create the file via:
$pdf = $_SERVER['DOCUMENT_ROOT'] . '/pdf/temp/temp.pdf';
$file = curl_file_create($pdf, 'application/pdf', 'receipt');`
or
$file = new CURLFile($pdf, 'application/pdf', 'receipt');
I've tried using:
$file = fopen($pdf, 'rb');
$file = array('file' => $file);
CURLOPT_POSTFIELDS => $file,
CURLOPT_INFILESIZE => $fileSize,
CURLOPT_INFILE => $file
No luck though.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://staging-tallie.com/v2/enterprise/ENTERPRISEID/MyReceipt/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => array(
"accept: application/json; charset=utf-8",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"token: TOKEN",
"upload-filename: receipt.pdf"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Error reads:
<?xml version="1.0" encoding="utf-8"?>
<ErrorResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseCode>400</ResponseCode>
<Message>Unable to Save the file to the Storage Service.</Message>
</ErrorResponse>
400 is an HTTP response code indicating that the request was impossible to satisfy. That, along with the accompanying message text, suggest that the PHP process does not have write access to the destination directory.
This code worked for me in order to upload a file to bluemix Cloud Object Storage. File is uploaded from temporary folder after form submit using PUT method. Don't forget to validate file mime and extension before upload.
if (is_uploaded_file($_FILES['my_file']['tmp_name'])){
$ch = curl_init();
$url = IBM_BLUEMIX_BUCKET_END_POINT.$bucket_name."/".$file_name; // give the file a unique name
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_PUT, true); //PUT REQUEST
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-amz-acl: public-read', //header required for bluemix
'Authorization: Bearer '.$access_token, // authorization for bluemix iam
'Content-Type: '.$conten_type, //application/pdf or image/jpg
'Expect: '
));
$image_or_file = fopen($_FILES['my_file']['tmp_name'], "rb");
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $image_or_file);
curl_setopt($ch, CURLOPT_INFILESIZE, $_FILES[$fieldName]['size']);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
array(
'file' =>
'#' . $_FILES['my_file']['tmp_name']
. ';filename=' . $_FILES['my_file']['name']
. ';type=' . $conten_type //application/pdf or image/jpg
));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,16);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$response = curl_exec($ch);
$headerSent = curl_getinfo($ch ); // request headers from response (check if something wrong)
curl_close ($ch);
fclose($image_or_file);
if(!$response){ // or response
// do something...
}
}else{
//File did not upload, do something ...
}

CURL is not working to send GET request in php

I am using CURL to send get request to a server, but it is not producing the required output.
The script works fine when loaded in browser.
It is script which combines given PNG images to GIF.
<?php
//generate GIF
$name = $_GET['name_of_final_gif'];
$images = $_GET['images'];
$images = json_decode($images, true);
//include GIF maker class based on GD library
include('GIFEncoder.class.php');
/******************************************************/
foreach($images as $image_link) {
// Open the source image and add the text.
$image = imagecreatefrompng($image_link);
// Generate GIF from the $image
// We want to put the binary GIF data into an array to be used later,
// so we use the output buffer.
ob_start();
imagegif($image);
$frames[]=ob_get_contents();
$framed[]=300; // Delay in the animation.
ob_end_clean();
}
// Generate the animated gif and save it
$gif = new GIFEncoder($frames,$framed,0,2,0,0,0,'bin');
$fp = fopen("gifs/$name", 'w');
fwrite($fp, $gif->GetAnimation());
fclose($fp);
?>
Update:
Below is my CURL code which is on another server and is sending GET request to this script which is hosted on another server:
$images = $class_name->get_images_links(); // get image links from database in JSON FORMAT
$name = "something.gif"; //name for output GIF image
$url = "http://example.com/make_gif.php?images=$images&&name_of_final_gif=$name";
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
Try this
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/make_gif.php?images=$images&&name_of_final_gif=$name");
curl_exec($ch);
curl_close($ch);
Try this:
function curl($url) {
// Assigning cURL options to an array
$options = Array(
CURLOPT_RETURNTRANSFER => TRUE, // Setting cURL's option to return the webpage data
CURLOPT_FOLLOWLOCATION => TRUE, // Setting cURL to follow 'location' HTTP headers
CURLOPT_AUTOREFERER => TRUE, // Automatically set the referer where following 'location' HTTP headers
CURLOPT_TIMEOUT => 120, // Setting the maximum amount of time for cURL to execute queries
CURLOPT_MAXREDIRS => 10, // Setting the maximum number of redirections to follow
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8", // Setting the useragent
CURLOPT_URL => $url, // Setting cURL's URL option with the $url variable passed into the function
);
$ch = curl_init(); // Initialising cURL
curl_setopt_array($ch, $options); // Setting cURL's options using the previously assigned array data in $options
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
$page = curl($link);

cURL Download Zip File - " argument is not a valid File-Handle resource"

I'm trying to download a zip file from a server I host and store it on another server using PHP and cURL. My PHP looks like this:
set_time_limit( 0 );
$ci = curl_init();
curl_setopt_array( $ci, array(
CURLOPT_FILE => '/directory/images.zip', // File Destination
CURLOPT_TIMEOUT => 3600, // Timeout
CURLOPT_URL => 'http://example.com/images/images.zip' // File Location
) );
curl_exec( $ci );
curl_close( $ci );
Whenever I run this I get the following error on the CURLOPT_URL line:
Warning: curl_setopt_array(): supplied argument is not a valid File-Handle resource in ...
If I visit the File Location directly in my browser, it downloads. Do I need to pass some kind of header information so that it knows to that it's a zip file? Is there some kind of way I can debug this?
Your problem is that you have to pass a filehandle to CURLOPT_FILE, not the filepath. Here is a working example
$ci = curl_init();
$url = "http://domain.com/images/images.zip"; // Source file
$fp = fopen("/directory/images.zip", "w"); // Destination location
curl_setopt_array( $ci, array(
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 3600,
CURLOPT_FILE => $fp
));
$contents = curl_exec($ci); // Returns '1' if successful
curl_close($ci);
fclose($fp);

Categories