I am using windows azure blob storage service to store data. My php file is this
<?php
require_once __DIR__ . '/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;
// Create blob REST proxy.
$connectionString = "[CONNECTION STRING (WORKS)]";
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blob_name = "myblob";
// Create blob REST proxy.
try {
//Upload blob
$blobRestProxy->createBlockBlob("containerName",$blob_name, $_FILES['userfile']['tmp_name']);
echo '104';
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
?>
The BLOB is created perfectly...
The only problem i'm having is when I use $_FILES['userfile']['tmp_name'] it actually stores in the BLOB the PATH of the file, not the contents of the file itself.
My question is, how can I store a BLOB using the $_FILES contents?
You need to read the contents of the file using file_get_contents() or other method:
$blob_content = file_get_contents($_FILES['userfile']['tmp_name']);
$blobRestProxy->createBlockBlob("containerName", $blob_name, $blob_content);
MS actually attempts to give an example here, however fopen() doesn't work like that.
Related
I'm trying to follow this link: https://learn.microsoft.com/en-us/rest/api/storageservices/copy-file
with examples from this repo: https://github.com/Azure/azure-storage-php/blob/master/samples/FileSamples.php#L235
The file is indeed copied to the azure server but the content aren't readable, to say the least, it takes a size but it's empty. This is only a text file as well, and what I plan to achieve after fixing this is to copy excel files generated via PHP to an azure file storage server.
Also, we are using file.core not blob.core
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\File\FileRestProxy;
use MicrosoftAzure\Storage\Common\Models\Range;
$accountName = "test";
$accountKey = "test";
$shareName = 'test';
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$accountName;AccountKey=$accountKey";
$fileClient = FileRestProxy::createFileService($connectionString);
$dstfileName = 'demo-4.txt';
$srcfileName = 'demo-4.txt';
$sourcePath = sprintf(
'%s%s/%s',
(string)$fileClient->getPsrPrimaryUri(),
$shareName,
$srcfileName
);
try {
// Create destination file.
$fileClient->createFile($shareName, $dstfileName, 1024);
// Copy file.
return $fileClient->copyFile($shareName, $dstfileName, $sourcePath);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
}
Update using file_get_contents
$srcfileName = 'demo-4.txt';
$content = file_get_contents('demo-4.txt');
$range = new Range(0, filesize('demo-4.txt') - 1);
$sourcePath = sprintf(
'%s%s/%s',
(string)$fileClient->getPsrPrimaryUri(),
$shareName,
$srcfileName
);
try {
// Create source file.
$fileClient->createFile($shareName, $srcfileName, 1024);
$fileClient->putFileRange($shareName, $srcfileName, $content, $range);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
}
This is able to create the file with the content from the source file, but the problem is that the range is incorrect since I don't know how to correctly get that value.
The created file is presented by the image attached, it has multiple nulls in it because I'm guessing my range exceeds the actual length of the source file contents.
createFile method simply creates an empty file of size specified in the method call. It essentially maps to Create File REST API operation.
You should use createFileFromContent convenience method to create a file with content. It basically first creates an empty file and then writes the contents to that file.
Other option would be to call putFileRange method to write the contents to the file after you have created it using createFile method.
I'm developing a WordPress plugin that requires to upload an excel file and then read the data inside of it.
I'm using the function "media_handle_upload" to upload the excel file, then, when I try to use SpreadsheetReader to read the file there's an error saying that the file is not readable.
This is what I'm coding, (I know it's horrible coding, but I'm learning and this is just to get the plugin working)
if(isset($_FILES['test_upload_pdf'])){
$pdf = $_FILES['test_upload_pdf'];
// Use the wordpress function to upload
// test_upload_pdf corresponds to the position in the $_FILES array
// 0 means the content is not associated with any other posts
$uploaded=media_handle_upload('test_upload_pdf', 0);
// Error checking using WP functions
if(is_wp_error($uploaded)){
echo "Error uploading file: " . $uploaded->get_error_message();
}else{
echo $pdf."<br>";
$year = date('Y');
$month = date('m');
$targetPath = get_site_url()."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
$targetPath2 = $_SERVER['DOCUMENT_ROOT']."/".$_SERVER["HTTP_HOST"]."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
echo "<br>";
echo $targetPath2;
echo "<br>";
try
{
$Reader = new SpreadsheetReader($targetPath2);
}
catch (Exception $E)
{
echo $E -> getMessage();
}
I think the reader doesn't work because is trying to access "localhost" instead of the physical folder, for example, one of the $targetPath prints this:
http://127.0.0.1/wordpress/wp-content/uploads/2019/04/example.xlsx
So... My question is, there's a way to access the media files so I can open them with the reader?
Thanks.
Perhaps this helps:
https://developer.wordpress.org/reference/functions/wp_upload_dir/
Otherwise try to hardcode folder "/your/path/to/upload/folder/file.extension" and find out how to create this programmaticly
okay i someone find out how to upload blobs in container of using php on azure, but when even i view the image with plain url like https://my.blob.url.net/my_image_folder/my_image_name.jpg the browser prompts to download the image, instead of viewing the image, like normal image is viewed on browser, here is the code i'm using while uploading
<?php
require_once __DIR__.'/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
$connectionString = 'DefaultEndpointsProtocol=http;AccountName=account_name;AccountKey=my_key_value';
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$content = fopen('folder/image.jpg','r');
$blob_name = 'image_name.jpg';
try
{
$blobRestProxy->createBlockBlob("container_name", $blob_name, $content);
}
catch(ServiceException $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
this code is working fine, but when accessing the url, it prompts download option, which means i cannot use for img html tag
You have to set the blob's content type to an appropriate mime type. The following is a snippet in C# that shows how this can be done:
entryData.DestinationBlob.Properties.ContentType = "image/jpeg";
entryData.DestinationBlob.SetProperties();
We need to set its property Content type through Blob Options class.
PHP :
namespace - use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
//use code where you are creating blob
$opts = new CreateBlobOptions();
//$opts->setCacheControl('test');
$opts->setContentEncoding('UTF-8');
$opts->setContentLanguage('en-us');
//$opts->setContentLength(512);
$opts->setContentMD5(null);
$opts->setContentType($mimeType);
$blobRestProxy->createBlockBlob($containerName, $indexFile, $content,$opts);
$mimeType is Type of your file text/html, text/pdf. It will work in git.
package : "microsoft/windowsazure": "^0.5"
am uploading a Pdf file and passing it to getExtact function to extract pages from file which is being uploaded if any error in extraction we will send the file to decryptPDF function for which the input parameters are filename and filetempname for both the functions but here am using a file upload process i want to use file url like www.domainname.com/docs/1.pdf so that all the functions which are written already can be used : Below is my code
//here for the above variable values are coming from uploaded file here i want to use file url and all the pdf are in my own server
$FileName = $_FILES['inputfile']['name'];
$TempFileName = $_FILES['inputfile']['tmp_name']; $Folderpath='/home/domain/public_html/pdftest/temp';
try {
.
GetExtract($TempFileName,$FileName);
} catch (Exception $e) {
$responce = DecryptPDF($Folderpath,$Filename,$TempFileName);
if($responce == ''){
$Inputfile = $Folderpath.'/un_'.$Filename;
GetExtract($Inputfile,$FileName);
}else{
echo $responce;
}
As per my knowledge,local server $PATH is "/var/www/".Try putting your inputfiles in that location.Then only you can access the files using url.
I have set up an windows azure website (php), and I want to connect to the azure storage (blob) environment. I walked through the How to use the Blob service from PHP tutorial, but that only mentions the case when the website is stored localy.
I tried to set up a few cases, but i'm constantly getting a http 500 error.
<?php
require_once 'WindowsAzure/WindowsAzure.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
//$connectionString = "\WindowsAzure\Blob\Internal\IBlob";
// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString); // the code gets stuck at this line, result is a HTTP 500 error
$content = fopen("C:\Users\Public\Pictures\Sample%20Pictures\Woestijn.jpg", "r");
$blob_name = "newBlob";
try {
//Upload blob
$blobRestProxy->createBlockBlob("default", $blob_name, $content);
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}?>
Is there anyone who had a similar problem and managed to figure it out?
EDIT:
I now narrowed down the error search. I went into the ServicesBuilder.php file, and commented out line by line, until the page stopped to work. The line it went wrong at is $httpClient, as shown below:
public function createBlobService($connectionString)
{
$settings = StorageServiceSettings::createFromConnectionString(
$connectionString
);
$httpClient = $this->httpClient();
$serializer = $this->serializer();
$uri = Utilities::tryAddUrlScheme(
$settings->getBlobEndpointUri()
);
From what I'm seeing you're filling up the $connectionString variable with this value: "\WindowsAzure\Blob\Internal\IBlob" (even though it's commented - so probably you're passing it from somewhere else). If that's the case you'll need to change it.
The connection string should be a reference to your storage account containing the protocol, the name of the account and the key (you can find the name and the key in the portal):
$connectionString = "DefaultEndpointsProtocol=https;AccountName=jeroensaccount;AccountKey=fjmezfjmIOFJEZIOPAFJAZOPIFJAIMO"