I want to create directory and sub directory in azure storage from php and get that directory. This is my code.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connection_string);
$content = fopen("abc.txt", "r");
$blob_name = "dir1/dir2/di3/myblob";
try {
//Upload blob
$blobRestProxy->createBlockBlob("mycontainer", $blob_name, $content);
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
I want to get directory "dir1".I checked that example How to create a sub container in azure storage location.
But it's not in php. Can any one help me how can we create and get directory in azure from PHP code.
You can use ListBlobsOptions to set specially object when querying Blobs from container. Per your requirement, you can use the setDelimiter('/') of this options to set the delimiter as to separate the virtual directory from blob names.
And to use getBlobPrefixes() to get the virtual directory names from ListBlobsResult which is the result of listBlobs() function.
Please consider the following code snippet:
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
$listBlobsOptions = new ListBlobsOptions();
$listBlobsOptions->setDelimiter('/');
$result = $blobClient->listBlobs(<container_name>, $listBlobsOptions);
foreach ($result->getBlobPrefixes() as $k => $b) {
//an instance of MicrosoftAzure\Storage\Blob\Models\BlobPrefix
array_push($return['blobPrefixes'], $b->getName());
}
And here is a sample about how to use the modules in Azure Staoge SDK for PHP. You can have a full glance of the usage from https://github.com/Azure-Samples/storage-blob-php-webapplication/blob/master/PHP/api/trial.php#L163.
Any further concern, please feel free to let me know.
Related
I currently have a script which loops through a google drive folder and does various things, one of which is to sync files uploaded/updated on gdrive with the files on the server. The script decides it wants a file, and uses the following function to write it to the server:
function get_file($file, $service, $docroot, $area){
$errorthrown = false;
try {
$getFile = $service->files->get($file->id, array('alt' => 'media'));
$content = $getFile->getBody()->getContents();
$handle = fopen($docroot.'file/'.$area.'/'.$file->name,"w");
fwrite($handle, $content);
fclose($handle);
} catch (\Throwable $e) {
print "The Google Drive API threw an error, but dont worry, we'll come back for this.";
return "error";
}
}
Now I would like to offer a file manager on the server which allows users to pick files, including those on the server and those which aren't. Is there a way of forcing the download of files returned from the google drive API, without first fwrite()ing?, for example using readfile() or fpassthru()?
I have tried various things with readfile() but from google drive I have the file contents, but no path to the file itself.
Any ideas?
Thanks a lot.
I created one folder and inside that folder I've created 2 text files, with some text inside. I can also list the files and get the text in them without problems. Now I am trying to update the text inside of that files, but I am always getting this error:
"domain": "global",
"reason": "fieldNotWritable",
"message": "The resource body includes fields which are not directly writable."
I created a function similar to the one presented in https://developers.google.com/drive/v2/reference/files/update.
I used this example because in version v3, Google don't present any example, and I can't find anything that can help me in this. My function is below.
function updateFile ($service, $fileId, $newTitle, $newDescription, $newMimeType, $text) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setName($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$additionalParams = array(
'data' => $text,
'uploadType' => 'media'
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Thank you in advance.
Based from this SO answer, on v3, using update like that throws the error fieldNotWritable.
The solution is to create an empty File setting only the new values:
File newContent = new File();
newContent.setTrashed(true);
service.files().update(fileId, newContent).execute();
Note: File refers to com.google.api.services.drive.model.File (it is not java.io.File).
Also, based from this documentation, you can see that shared isn't a writable field. You can share a file by adding a new permission, and you can check if a file has been shared by reading the shared property. But saying a file is shared, other than by actually sharing it, makes no sense. [Source.]
Simple question; how do you check if a blob exists using PHP in Azure blob storage using the file name? I can't seem to find it in the API.
Cheers
I was looking for this today and this was the top search result so wanted to give my solution here which uses the prefix option to find only blobs which match the name I'm looking for.
You will need to include use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions; as well.
function blobExists($name)
{
global $blobClient, $blobContainer;
$listBlobsOptions = new ListBlobsOptions();
$listBlobsOptions->setPrefix($name);
$result = $blobClient->listBlobs($blobContainer, $listBlobsOptions);
return count($result->getBlobs());
}
Use the PHP SDK for Azure.
/ Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
// Get blob.
$blob = $blobRestProxy->getBlob("mycontainer", "myblob");
if ($blob) {
//blob exists
}
Solution for those using PHP SDK v4.10
http://phpazure.codeplex.com/
$storageClient = $this->azure->get_blob_storage();
//check if blob exists
$exists = $storageClient->blobExists(<container name>, <blob name>);
Go into the blob.php inside the SDK folder to see a complete list of API functions.
I am trying to follow a tutorial on converting doc to pdf using openoffice. I have the following code:
<?php
set_time_limit(0);
function MakePropertyValue($name, $value,$osm){
$oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
$oStruct->Name = $name;
$oStruct->Value = $value;
return $oStruct;
}
function word2pdf($doc_url, $output_url){
// Invoke the OpenOffice.org service manager
$osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
// Set the application to remain hidden to avoid flashing the document onscreen
$args = array(MakePropertyValue("Hidden",true,$osm));
// Launch the desktop
$top = $osm->createInstance("com.sun.star.frame.Desktop");
// Load the .doc file, and pass in the "Hidden" property from above
$oWriterDoc = $top->loadComponentFromURL($doc_url,"_blank", 0, $args);
// Set up the arguments for the PDF output
$export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
// Write out the PDF
$oWriterDoc->storeToURL($output_url,$export_args);
$oWriterDoc->close(true);
}
$output_dir = './';
$doc_file = './test.docx';
$pdf_file = 'DpmR5Reqv1.20.pdf';
$output_file = $output_dir . $pdf_file;
$doc_file = 'file:///' . $doc_file;
$output_file = 'file:///' . $output_file;
word2pdf($doc_file,$output_file);
?>
I get the error:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager' in C:\wamp\www\Projects\doc_to_pdf\index.php on line 11
( ! ) com_exception: Failed to create COM object `com.sun.star.ServiceManager': Invalid syntax in C:\wamp\www\Projects\doc_to_pdf\index.php on line 11
Ive tried to what this tutorial suggests: http://puno.ayun.web.id/2009/08/php-ooo-in-microsoft-windows-environment/ But no luck. Any idea what I can do? I am running this under wamp and it will be ran under wamp in production.
You have to have OpenOffice setup to run as a service on that machine. To simply convert an odt to a pdf you can use pyodconverter. They also explain how to setup the local OpenOffice service:
http://www.artofsolving.com/opensource/pyodconverter
I'm using this technique in a script I wrote and have an article for here:
http://codeuniversity.com/scripts/scr1
Please install Open Office in your Directory. OpenOffice setup to run as a service on that machine.
it is much easier to use headless libreoffice and a php wrapper class like https://github.com/ncjoes/office-converter.
of course you have to install libreoffice and you must have full control of your webserver.
So I have a client who's current host does not allow me to use tar via exec()/passthru()/ect and I need to backup the site periodicly and programmaticly so is there a solution?
This is a linux server.
PHP 5.3 offers a much easier way to solve this issue.
Look here: http://www.php.net/manual/en/phardata.buildfromdirectory.php
<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
?>
At http://pear.php.net/package/Archive_Tar you can donload the PEAR tar package and use it like this to create the archive:
<?php
require 'Archive/Tar.php';
$obj = new Archive_Tar('archive.tar');
$path = '/path/to/folder/';
$handle=opendir($path);
$files = array();
while(false!==($file = readdir($handle)))
{
$files[] = $path . $file;
}
if ($obj->create($files))
{
//Sucess
}
else
{
//Fail
}
?>
There is the Archive_Tar library. If that can't be used for some reason, the zip extension might be another option.
I need a solution that would work on Azure websites (IIS) and had trouble with creating new files on the server using methods from other answers. The solution that worked for me was to use small TbsZip library for compression, which doesn't require to write file anywhere in the server - it's just returned directly via HTTP.
This thread is old, but this approach might be a bit more generic and complete answer, so I post the code as alternative:
// Compress all files in current directory and return via HTTP as a ZIP file
// by buli, 2013 (http://buli.waw.pl)
// requires TbsZip library from http://www.tinybutstrong.com
include_once('tbszip.php'); // load the TbsZip library
$zip = new clsTbsZip(); // instantiate the class
$zip->CreateNew(); // create a virtual new zip archive
// iterate through files, skipping directories
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($objects as $name => $object)
{
$n = str_replace("/", "\\", substr($name, 2)); // path format
$zip->FileAdd($n, $n, TBSZIP_FILE); // add fileto zip archive
}
$archiveName = "backup_".date('m-d-Y H:i:s').".zip"; // name of the returned file
$zip->Flush(TBSZIP_DOWNLOAD, $archiveName); // flush the result as an HTTP download
And here's the whole article on my blog.