I have tried to use file_get_contents() and also curl to do this .. But both of these functions download the file temporarily to my pc and then upload to drive ...
Is there any way in which i can directly upload file from the url to my drive ?
Here is one code i tried :
$file = new Google_DriveFile();
$file->setTitle('My app');
$file->setDescription('Application');
$file->setMimeType('application/exe');
$url = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.exe";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec ($ch); // execute
curl_close ($ch); // close curl handle
$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' => 'application/exe',));
Here is another one :
$file = new Google_DriveFile();
$file->setTitle('My app');
$file->setDescription('Application');
$file->setMimeType('application/exe');
$url = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.exe";
$data = file_get_contents($url);
$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' => 'application/exe',));
Both of these codes are downloading the files first to my pc ... then they start uploading
When you pass a URL in stead of a local file path to file_get_contents() or curl_init(), PHP will automatically attempt to download the file that the URL points to.
All you need to do to prevent this is to change the value of $url to a local file path:
$url = '/tmp/somefile.txt'; // *nix
$url = 'c:/somefile.txt'; // Windows
Related
I am getting the response by Third party API call. They providing me a file_url in response. If I hitting the file_url in browser URL got the zip file on local machine.
stdClass Object
(
[start_date] => 2018-06-01 08:00:00
[report_date] => 2018-07-02
[account_name] => Maneesh
[show_headers] => 1
[file_url] => https:examplefilename
[date_range] => 06/01/2018 - 07/03/2018
)
How can I download the zip file on public/phoneList folder on server and unzipped the file?
$fileUrl = $rvmDetails->file_url;
$zip = realpath('/phoneList/').'zipped.zip';
file_put_contents($zip, file_get_contents($fileUrl));
$zip = new \ZipArchive();
$res = $zip->open('zipped.zip');
if ($res === TRUE) {
$zip->extractTo('/phoneList/'); // phoneList is folder
$zip->close();
} else {
echo "Error opening the file $fileUrl";
}
The above code works. but getting issue while unzipp the folder.
ZipArchive::extractTo(): Permission denied
With the PHP build-in system you can open/extract zips in a certain path and download it with CURL (you should create a filename too), like:
$fileUrl = $obj->file_url;
$fileName = date().".zip"; //create a random name or certain kind of name here
$fh = fopen($filename, 'w');
$ch = curl_init()
curl_setopt($ch, CURLOPT_URL, $fileUrl);
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
curl_exec($ch);
curl_close($ch);
fclose($fh);
// get the absolute path to $file
$path = pathinfo(realpath($filename), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
$zip->extractTo($path);
$zip->close();
} else {
echo "Error opening the file $file";
}
You can find more info here: download a zip file from a url and here: Unzip a file with php
Hope it helps!
I am using PHP CURL to generate a customized PNG image from a REST API. Once this image has loaded I would like to upload it into an AWS S3 Bucket and show the link to it.
Here's my script so far:
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'http://url-to-generate-image.com?options=' + $_GET['options']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
//require S3 Class
if (!class_exists('S3')) {
require_once('S3.php');
}
//AWS access info
if (!defined('awsAccessKey')) {
define('awsAccessKey', 'MY_ACCESS_KEY');
}
if (!defined('awsSecretKey')) {
define('awsSecretKey', 'MY_SECRET_KEY');
}
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket('bucket-name', S3::ACL_PUBLIC_READ);
$file_name = md5(rand(99,99999999)) + '-myImage.png';
if ($s3->putObjectFile($data, 'bucket-name' , $file_name, S3::ACL_PUBLIC_READ)) {
echo 'success';
$gif_url = 'http://bucket-name.s3.amazonaws.com/'.$file_name;
} else {
echo 'failed';
}
It keeps failing. Now, I think the problem is with where I use putObjectFile - the $data variable represents the image, but maybe it has to be passed in another way?
I am using a common PHP Class for S3: http://undesigned.org.za/2007/10/22/amazon-s3-php-class
Use PHP memory wrapper to store the contents of the image, and use $s3->putObject() method:
$fp = fopen('php://memory', 'wb');
fwrite($fp, $data);
rewind($fp);
$s3->putObject([
'Bucket' => $bucketName,
'Key' => $fileName,
'ContentType' => 'image/png',
'Body' => $fp,
]);
fclose($fp);
Proven method (you may need to alter the code a bit) with PHP 5.5 and latest AWS libraries.
http://php.net/manual/en/wrappers.php.php
1 - I have configure google picker and it is working fine and I select the file from picker and get the file id.
2 - After refresh token etc all process I get the file metadata and get the file export link
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
3 - After that I use this
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200)
{
$content = $httpRequest->getResponseBody();
print_r($content);
} else {
// An error occurred.
return null;
}
and get this response
[responseBody:protected] => PK��DdocProps/app.xml���
�0D���k�I[ѫ��m
��!����A={���}�
2G�Z�g�V��Bľ֧�n�Ҋ�ap!����fb�d����k}Ikc�_`t<+�(�NJ̽�����#��EU-
�0#���P����........
4 - I use some cURL functions to get file from google drive and save it to server. IN server directory a file created but cropped. I use this code
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
//$downloadUrl value is
/*https://docs.google.com/feeds/download/documents/export/Export?id=1CEt1ya5kKLtgK************IJjDEY5BdfaGI&exportFormat=docx*/
When I put this url into browser it will download file successfully but when I use this url to fetch file with cURL or any php code and try to save it on server it saves corrupted file.
$ch = curl_init();
$source = $downloadUrl;
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "test/afile5.docx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
It result a corrupted file stored on server but whe I use this code to get any file other then google drive I download it successfully on server.
Can any one please help that how to download file from $downloadUrl to my server using php ?
I'm trying to run PHP script (from a Linux server) that will download a file through direct download link and save it on my server.
here is the script I'm using:
<?php
$url = 'http://download.maxmind.com/app/geoip_download?edition_id=108&date=20131015&suffix=zip&license_key=XXXXXXXXXXX';
$path = '/apps/test/';
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
for some reason it doesn't work for me, any suggestions ?
You need to verify that the ports are open on your firewall and use the below command:
(this will also download the file in the original format)
shell_exec("wget -P /apps/birst/php_test_scripts/ --content-disposition "."'"."https://download.maxmind.com/app/geoip_download?edition_id=108&suffix=zip&license_key=XXXXXXXX"."'");
Why dont you just use :
shell_exec("wget -P /target/directory/ http://download.link.com/download.zip");
Try this
$url = 'http://download.maxmind.com/app/geoip_download?edition_id=108&date=20131015&suffix=zip&license_key=XXXXXXXXXXX';
$path = '/apps/test/';
$filepath = $path .'file.zip';
$data = file_get_contents($url);
file_put_contents($filepath, $data);
I am using csxi to make scanning for documnets as image, but I have to upload pdf files to server. How can I convert image to PDF in php ? or is there any way to make csxi scan documents as PDF not image
If you have ImageMagick installed on your machine you could use the ImageMagick bindings for PHP to execute some simple PHP code to do this task:
$im=new Imagick('my.png');
$im->setImageFormat('pdf');
$im->writeImage('my.pdf');
Alternatively if you don't have ImageMagick available you could use a commercial API such as Zamzar which supports image to PDF conversion via PHP (more info in the docs).
Code to use this would be:
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_API_KEY";
$sourceFilePath = "my.png";
$targetFormat = "pdf";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>
Wrap your image inside HTML and use some HTML to PDF converter like fpdf or mpdf
You can use convertapi service, easy to install:
composer require convertapi/convertapi-php
require_once('vendor/autoload.php');
use \ConvertApi\ConvertApi;
//get api key: https://www.convertapi.com/a/si
ConvertApi::setApiSecret('xxx');
$result = ConvertApi::convert('pdf', ['File' => '/dir/test.png']);
# save to file
$result->getFile()->save('/dir/file.pdf');
to convert multiple files and other options check https://github.com/ConvertAPI/convertapi-php
Here, Php 7.4, Laravel 7+, ImageMagick-7.1.0-Q16, and Ghostscript gs10.00.0 is used.
If any files are contained in the folder JpgToPdf then delete them. And so on.
/**
* jpg To pdf WEB
*
* #method convertJpgToPdf
*/
public function convertJpgToPdf(Request $request)
{
try {
//get list of files
$files = Storage::files('JpgToPdf');
/*get count of files and ,
* check if any files contain
* if any files contains
* then
* get the files name
* delete one by one
*/
if(count($files) >1 )
{
foreach($files as $key => $value)
{
//get the file name
$file_name = basename($value);
//delete file from the folder
File::delete(storage_path('app/JpgToPdf/'. $file_name));
}
}
if ($request->has('jpeg_file'))
{
$getPdfFile = $request->file('jpeg_file');
$originalname = $getPdfFile->getClientOriginalName();
$path = $getPdfFile->storeAs('JpgToPdf', $originalname);
}
// file name without extension
$filename_without_ext = pathinfo($originalname, PATHINFO_FILENAME);
//get the upload file
$storagePath = storage_path('app/JpgToPdf/' . $originalname);
$imagick = new Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage($storagePath);
$imagick->setImageCompressionQuality( 100 );
$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$imagick->writeImage( storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
return response()->download(storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
} catch (CustomModelNotFoundException $exception) {
// Throws error exception
return $exception->render();
}
}
For just a few images, do it manually and easily with the Chrome web browser. You wont need an internet connection.
Save the following with .html extension in the same folder of your image:
<html>
<body>
<img src="image.jpg" width="100%">
</body>
</html>
Open the html file with Google Chrome,
Crtl + P, to open the print dialog
Choose Save as PDF, to save it locally
Alternatively, you could send a copy to your smatphone via Google Cloud Print