I need to download all the attachments on a Podio app. I can get all the files id and their url, etc.. i just can't make the download. I've tried many possible solutions (get_raw(), file_get_contents, etc..).
Lets say i have this file that i want to save:
$items = PodioFile::get_for_app(APP_ID, array(
'sort_by' => 'name',
'sort_desc' => 'false',
'limit' => 1
));
(...)
$item->file_id = '123456789'
$item->link = 'https://files.podio.com/111222333';
$path_to_save = 'backup/';
How can i save it?
There's an example ready for copy+paste at: http://podio.github.io/podio-php/api-requests/
// Get the file object. Only necessary if you don't already have it!
$file = PodioFile::get($file_id);
// Download the file. This might take a while...
$file_content = $file->get_raw();
// Store the file on local disk
file_put_contents($path_to_file, $file_content);
mkdirs("downloads");
foreach ($podio_item->fields['images']->values as $key => $podio_file) {
$file = PodioFile::get($podio_file->file_id);
$file_content = $file->get_raw();
file_put_contents("downloads/$podio_image->name", $file_content);
}
Related
The site is the CAISO OASIS and they use an old way of querying and returning datasets. 30 days at a time, zip file with enclosed *.csv files. I have tried for 4 days coming up with a way to automate this download first of the zip file but i cant even get past there.
If I populate the url string I want and enter it myself in the address bar a zip file will start downloading, I cannot for the life of me get it to do the same through code.
I need to use php to accomplish this task.
I have tried, fopen, file_get_contents, file_put_contents, cURL, ziparchive class. I have tried changing all sorts of things. The best I get is a download of a corrupt zip file that is empty.
Ideally i would love to extract the *.csv or xml file but I cannot even do the first basic step.
The following variable I populate, $url_caiso_qry, if you take the echo string and past in the browser and enter the zip file will start downloading, but I cannot download it automatically.
http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1
<?php
$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);
// creates data array for precio de carga SIN
// function create_dataarrayp_chrt($zona) {
$ayer = date("Ymd\T7:00-0000", strtotime('now - 1 day'));
$mespasado = date("Ymd\T7:00-0000",strtotime('-30 days'));
$sdate = $mespasado; //startdatetime=
$edate = $ayer; //enddatetime=
$resultformat = '6';
$queryname='SLD_FCST';
$version='1';
$marketrunid='ACTUAL';
$fields = [
'startdatetime' => $sdate,
'enddatetime' => $edate,
'resultformat' => $resultformat,
'queryname' => $queryname,
'market_run_id' => $marketrunid,
'version' => $version,
];
//post fields
$postparam = urldecode(http_build_query($fields));
//PRECIOS url base string
$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?';
//$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?resultformat=6&queryname=SLD_FCST&version=1&market_run_id=ACTUAL&startdatetime=' . $sdate . 'T07:00-0000&enddatetime=' . $edate . 'T07:00-0000';
$url_caiso_qry = $urlcaiso . $postparam;
$caisofile = file_get_contents($url_caiso_qry, "rb");
//attempt to write file to destination path, but no file is written. Instead the following warning
//Warning: file_put_contents(/name1/name2/private/test/):
// failed to open stream: No such file or directory in C:\xampp\htdocs\name1\name2\private\test.php on line 94
$destination_path = WWW_ROOT . 'name2/private/test/';
$newfile = file_put_contents($destination_path, $caisofile);
echo $newfile . '<br><br>';
?>
The second parameter you pass to file_get_contents describes the use_include_path according to the php documentation.
I tried this simple example to get the file and save it:
<?php
$content = file_get_contents('http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1');
file_put_contents('example.zip', $content);
Running file example.zip gives the following output:
example.zip: Zip archive data, at least v2.0 to extract which indicates success.
So essentially your final code could look something like this:
<?php
// Build url here
$url = 'http://oasis.caiso.com/...';
// Download file
$zipFile = file_get_contents($url);
$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);
$targetPath = WWW_ROOT . 'proj3-ampenergy/private/test/'; // This could be any other path where your file should be stored
// Write contents to file
file_put_contents($targetPath, $zipFile);
// Write extraction logic here
Clean & tested code. Your csv file will be extracted to your script's directory.
<?php
define('PATH_ZIP', __DIR__ . '/archive.zip');
$url = 'http://oasis.caiso.com/oasisapi/SingleZip?' . http_build_query
([
'startdatetime' => '20220109T7:00-0000',
'enddatetime' => '20220207T7:00-0000',
'resultformat' => '6',
'queryname' => 'SLD_FCST',
'market_run_id' => 'ACTUAL',
'version' => '1',
]);
$data = file_get_contents($url);
file_put_contents(PATH_ZIP, $data);
$zip = new ZipArchive;
if ($zip->open(PATH_ZIP) === true)
{
$zip->extractTo(__DIR__);
$zip->close();
}
I'd like to create a .zip archive, upload it to Amazon S3, then delete the created .zip from the server. Steps 1 and 2 are working great, but the delete step is returning:
unlink(temp/file.zip): Resource temporarily unavailable
I've tried to unset all the related variables and resources, but I'm still getting the error.
Here's the code:
$zipFile = 'temp/file.zip';
// create the zip archive:
$z = new \ZipArchive();
$z->open($zipFile, \ZipArchive::CREATE);
$z->addEmptyDir('testdirectory');
// add a file
$filename = 'fileName.txt';
$content = 'Hello World';
$z->addFromString('testdirectory/' . $filename, $content);
$z->close();
// upload to S3
$s3 = AWS::createClient('s3');
$result = $s3->putObject(array(
'Bucket' => 'my-bucket-name',
'Key' => basename($zipFile),
'SourceFile' => $zipFile
));
// check to see if the file was uploaded
if ($result['#metadata']['statusCode'] == "200") {
$uploaded = true;
}
// delete the temp file
if ($uploaded) {
unset($result);
unset($s3);
unset($z);
if (file_exists($zipFile)) {
unlink($zipFile);
}
}
Some additional details: I'm using Lumen 5.4 and the aws-sdk-php-laravel package.
Any insight would be much appreciated! Thanks.
S3 is holding resources so we have to forcefully clear the gc (Garbage Collector).
Just do gc_collect_cycles() before deleting that file.
Given the following snippet, I'm looping through and downloading an array of files. It appears if the file list is greater than 50 objects, well, that's it. Does Amazon have a limit on the number of objects I can download at one time? if so, is there a work around or am i just doing this wrong? Again, everything works fine for under 50 files.
Just to clarify, the intent is to generate a zip file for someone to download. the file list could vary from a couple of files to hundreds.
if ($zip->open($path, ZipArchive::CREATE)){
foreach($sheets as $sheet){
// the saved file name as it exists on the server...
$keyname = $sheet.".pdf";
// the new name of the file, what it was originaly uploaded as
$sql = "SELECT * FROM files WHERE id=$sheet";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$saveas = $row['number']."-".$row['name'].".pdf";
}
}
// Save object locally (downloads directory) to a file.
$filepath = "/var/www/html/downloads/".$saveas;
$result = $client->getObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SaveAs' => $filepath
));
// insert the recently saved file to the zip
$zip->addFile($filepath, $saveas);
}
}
I have a mail_merge function (using cakephp) which when called directly from the browser e.g.
domain.com/contacts/mail_merge will generate the PDF and save it to the server as needed with the database mapped fields.
When however I try to call this mail_merge function from another function. e.g. $this->mail_merge($cond, 1); The PDF won't generate. The database fields are still coming though to the mail_merge function so it's not this issue. Any idea why this might be happening? I have updated my code below to now include a simple generated txt file with the code I am trying to put onto the PDF and this works so there is simply something about mPDF that won't generate a PDF when called from a function.
Thanks
My mail_merge function is as follows:
// FUNCTION GENERATE MAIL MERGE - mPDF
// -------------------------------------------------------------->
function mail_merge($conditions=NULL, $mail_merge_id=1)
{
// REMOVE THE STANDARD LAYOUT
// ------------------------------------------------------>
$this->layout = null;
// GET THE CONTACTS
// ------------------------------------------------------------->
$contacts = $this->Contact->Card->find('all', array(
'limit' => 10,
//'fields' => $fields,
'contain' => array('Contact', 'Prospect', 'SaleDetail'),
'conditions' => $conditions
));
$this->set('contacts', $contacts);
// GE THE CONTENTS
// ------------------------------------------------------------>
$this->loadModel('MailMerge');
$content = $this->MailMerge->find('first', array(
'conditions' => array('MailMerge.id' => $mail_merge_id),
'fields' => array('MailMerge.description')
));
$this->set('content', $content);
// initializing mPDF
// --------------------------------------------------------------------------->
$this->Mpdf->init();
// RENDER THE VIEW AND SET AS A VARIABLE TO WRITE THE HTML
// --------------------------------------------------------------------------->
$response = $this->render('mail_merge');
$thebody = $response->body();
$this->Mpdf->WriteHTML($thebody);
// setting filename of output pdf file
// --------------------------------------------------------------------------->
$thefilename = "mail_merge_".date("d.m.Y_His").".pdf";
$this->Mpdf->setFilename(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename);
// setting output to I, D, F, S
// --------------------------------------------------------------------------->
$this->Mpdf->setOutput('F');
// TEMP - CREATE TXT FILE ON THE SERVER
// ------------------------------------------------------------------------>
$thefilenametxt = "mail_merge_".date("d.m.Y_His").".txt";
$ourFileHandle = fopen(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilenametxt, 'w');
fwrite($ourFileHandle, $thebody);
fclose($ourFileHandle);
return $thefilename;
} // END MAIL MERGE
I discovered the issue lied with the setOutput function of the component.
When I changed:
$this->Mpdf->setFilename(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename);
$this->Mpdf->setOutput('F');
To
$this->Mpdf->Output(APP. WEBROOT_DIR . "/files/csv_exports/" . $thefilename, 'F');
it worked as needed.
I have to send a file to an API. The API documentation provides an example of how to do this through a file upload script ($_FILES). But, I have the files on the same machine, so would like to skip this step and just read in the file directly to save time.
How can I read in the file (a video) so that it will work with this code snippet?
I understand that FILES is an array, but I could set the other parts of it (the filename) seperately, I just really need the data part of it to be read in the same format to work with this code (do I use fread? file get contents?)
<?php
# Include & Instantiate
require('../echove.php');
$bc = new Echove(
'z9Jp-c3-KhWc4fqNf1JWz6SkLDlbO0m8UAwOjDBUSt0.',
'z9Jp-c3-KhWdkasdf74kaisaDaIK7239skaoKWUAwOjDBUSt0..'
);
# Create new metadata
$metaData = array(
'name' => $_POST['title'],
'shortDescription' => $_POST['shortDescription']
);
# Rename the video file
$file = $_FILES['video'];
rename($file['tmp_name'], '/tmp/' . $file['name']);
$file_location = '/tmp/' . $file['name'];
# Send video to Brightcove
$id = $bc->createVideo($file_location, $metaData);
?>
Thanks in advance for any help!
Er - all you'd need to do is feed the location, not a file handle or anything, no?
$files = $_FILES['video'];
$filename = $files['name'];
$file_location = '/home/username/' . $filename; // maybe append the extension
$id = $bc->createVideo($file_location, $metaData);
Or more simply
$id = $bc->createVideo( '/foo/bar/baz.txt', $metaData );
Looks like you don't need to do anything except point at the file on your local disk. What about:
<?php
# Include & Instantiate
require('../echove.php');
$bc = new Echove(
'z9Jp-c3-KhWc4fqNf1JWz6SkLDlbO0m8UAwOjDBUSt0.',
'z9Jp-c3-KhWdkasdf74kaisaDaIK7239skaoKWUAwOjDBUSt0..'
);
# Create new metadata
$metaData = array(
'name' => $_POST['title'],
'shortDescription' => $_POST['shortDescription']
);
# point at some file already on disk
$file_location = '/path/to/my/file.dat'; // <== if the file is already on the box, just set $file_location with the pathname and bob's yer uncle
# Send video to Brightcove
$id = $bc->createVideo($file_location, $metaData);