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"
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 using the SSRS SDK For PHP which has not been updated since years surprisingly (08.04.2010) .
It works fine under PHP 5.4 (5.4.44) but not under 5.5+ (5.5.37, 5.6.28, 7.x)
The error is :
array ( )Failed to connect to Reporting Service Make sure that the url
(https://myHost:60004/ReportServer/) and credentials are
correct!
The exception is thrown in line 207 because the var $content is equals to FALSE (so can't load the content).
It's perfectly fine with PHP 5.4.44.
I can't find the "SSRS SDK For PHP" documentation regarding the PHP version supported...
I'm not using any framework such as Symfony2, CakePHP, Zend Framework,... except Bootstrap.
Does anyone know or have figured out this issue?
EDIT
As asked in a comment, here is my code :
function buildSSRSReport($companyId)
{
require_once '../tools/SSRSReport/SSRSReport.php';
try {
// Create a connection to the SSRS Server
$rs = new SSRSReport(new Credentials(SSRS_USER_ID, SSRS_PASSWORD), SSRS_REPORT_SERVER_URL);
$sqlConnection = self::getSqlConnection();
// Load the report and specify the params required for its execution
$executionInfo = $rs->LoadReport2(self::getSSRSEnvironment(), NULL);
$parameters = array();
$parameters[0] = new ParameterValue();
$parameters[0]->Name = "CompanyId";
$parameters[0]->Value = $companyId;
$rs->SetExecutionParameters2($parameters);
// Require the Report to be rendered in HTML format
$renderAsHTML = new RenderAsPDF();
// Set the links in the reports to point to the php app
//$renderAsHTML->ReplacementRoot = getPageURL();
// Set the root path on the server for any image included in the report
//$renderAsHTML->StreamRoot = './images/';
// Execute the Report
$result_html = $rs->Render2($renderAsHTML,
PageCountModeEnum::$Actual,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds);
$pdfFileName = self::getCompanyAlias($sqlConnection, $companyId) . ".pdf";
header('Content-Type: application/x-download');
header('Content-Disposition: attachment; filename="' . $pdfFileName . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
return $result_html;
} catch (SSRSReportException $serviceException) {
echo $serviceException->GetErrorMessage();
}
}
function getSSRSEnvironment()
{
return "/DEV/CompanyESGReportingServices-DEV/Main";
}
private function getSqlConnection()
{
require_once("../inc/eth_connexion.php");
/* These 4 variables are contained within the eth_connexion.php file */
$serverName = SQL_SERVERNAME;
$userName = SQL_USERNAME;
$dbName = SQL_DATABASENAME;
$password = SQL_PASSWORD;
// SQLSRV : Connection array used when calling SQL via sqlsrv_query
$connectionInfo = array("Database"=> SQL_DATABASENAME,
"UID"=> SQL_USERNAME,
"PWD"=> SQL_PASSWORD,
"ReturnDatesAsStrings" => true);
$sqlConnection = sqlsrv_connect($serverName, $connectionInfo);
if (!$sqlConnection) {
die('Can't log to the database');
}
return $sqlConnection;
}
And here is the source code of the SSRSReport constructor (original from the SSRS SDK For PHP) :
public function SSRSReport($credentials, $url, $proxy = null)
{
$this->_BaseUrl = ($url[strlen($url) - 1] == '/')? $url : $url . '/';
$executionServiceUrl = $this->_BaseUrl . self::ExecutionService;
$managementServiceUrl = $this->_BaseUrl . self::ManagementService;
$options = $credentials->getCredentails();
$stream_conext_params = array( 'http' =>
array('header' =>
array($credentials->getBase64Auth())));
if(isset($proxy))
{
$options = array_merge($options, $proxy->getProxy());
$stream_conext_params['http']['proxy'] = 'tcp://' .
$proxy->getHost() .
':' .
$proxy->getPort();
if($proxy->getLogin() != null)
{
$stream_conext_params['http']['header'][1] = $proxy->getBase64Auth();
}
}
/**
* If the SoapClient call fails, we cannot catch exception or supress warning
* since it throws php fatal exception.
* http://bugs.php.net/bug.php?id=34657
* So try to load the wsdl by
* calling file_get_contents (with warning supressed i.e. using # symbol
* infront of the function call)
* http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-filegetcontents-function-in-php
*/
$context = stream_context_create($stream_conext_params);
$content = #file_get_contents($executionServiceUrl, false, $context);
if ($content === FALSE) // I'M GOING HERE WITH PHP 5.5+
{
throw new SSRSReportException("",
"Failed to connect to Reporting Service <br/> Make sure " .
"that the url ($this->_BaseUrl) and credentials are correct!");
}
$this->_soapHandle_Exe = new SoapClient ($executionServiceUrl, $options);
$this->_soapHandle_Mgt = new SoapClient ($managementServiceUrl, $options);
$this->ClearRequest();
}
The exact error message is :
https://myPublicHostProvider:60004/ReportServer/ReportExecution2005.asmx?wsdl
Authorization: Basic = array(1) {
["http"]=> array(1) { ["header"]=> array(1) { [0]=> string(57)
"Authorization: Basic =" } } }
Failed to connect to Reporting Service
Make sure that the url (https://myPublicHostProvider:60004/ReportServer/) and credentials are correct!
SSRS SDK for PHP Configuration Pointers
Make sure your Report Server instance is accessible. Test it by going to the Web Portal or the Service URL.
Provide your credentials. If you are authenticated, then the credentials that you used are valid.
After that, go to the directory \Program Files\Microsoft SQL Server\<INSTANCE_NAME>\Reporting Services\ReportServer and look for the file named rsreportserver.config
Find this snippet
<Authentication>
<AuthenticationTypes>
<RSWindowsNTLM/>
</AuthenticationTypes>
<Authentication>
Add <RSWindowsBasic/> below the <RSWindowsNTLM/> entry.
For your reference, this was the snippet I used to test my instance during configuration.
require_once( 'SSRSReport\bin\SSRSReport.php' );
define( 'UID', 'DOMAIN\Username' );
define( 'PASWD', 'Password' );
define( 'SERVICE_URL', 'http://127.0.0.1/SERVICE_URL/' );
try {
$ssrs_report = new SSRSReport( new Credentials( UID, PASWD ), SERVICE_URL );
$ssrs_report->LoadReport2( '/test', NULL );
$renderAsHTML = new RenderAsHTML();
$result_html = $ssrs_report->Render2(
$renderAsHTML,
PageCountModeEnum::$Estimate,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds
);
echo $result_html;
} catch ( SSRSReportException $serviceException ) {
echo $serviceException->GetErrorMessage();
}
It can successfully load the RDL that is located on the load path.
Thanks for your help MiSAKACHi. It pointed me on the right direction. Actually, I'm using a remote dedicated server on a hosting provider on which I don't have access. But the <RSWindowsBasic/> is there as it can load the report with PHP 5.4. Everything is fine under this version.
Thanks to you, I found the issue : I'm using HTTPS and with HTTPS it doesn't work whereas it works when I'm using HTTP !
I'm check with my hosting provider if they can do something.
EDIT - Solution
My hosting provider fixed the issue last year (forgot to post it here). During the time it wasn't fixed, I was still under PHP 5.4.
I paste their original message :
These issues that you describe is because the installed Certificate is a self signed Certificate. New Web Browsers and PHP Version don't accept these Certificates because of Security Risks.
We have changed the Certificate with a official issued Certificate
I just want to add that I was facing issue using the codeplex ssrsphp, therefore I googled and found another sdk, which works perfectly. I'm using php 7+. Here is the link and I'm available if there're any questions related to this.
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"
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.
Just wondering if anyone knows of a prewritten php script to to transfer files from rackspace cloud site to rackspace cloud files.
Rackspace does provide a script to backup files to the cloud but not transfer. (and I only realized that after spending a couple of hours and finally getting the script working).
http://www.rackspace.com/knowledge_center/article/how-to-use-cron-to-backup-cloudsites-to-cloudfiles
I don't know PHP (which is required for Rackspace cron jobs), so if there's a script that would help me with this it would be great.
Thanks.
Below is the script I use when I backup to rackspace. It uses the php cloud files master library from racker labs. I set it up as a simple cron. Simply replace the emai
php 'path/to/backup.php'
<?
require_once('php-cloudfiles-master/cloudfiles.php');
$server_name = 'YOUR_SERVER_NAME'; //Name of the Current Server
$curr_date_time = date("Y-m-d--H:i:s"); //DON' CHANGE - Date
$curr_day = date("Yd"); //DON' CHANGE - Date
$sites = array("ENTERDATABASES HERE IN ARRAY FORMAT"); //Array of Databases to be Backed up
$site_root = "/var/www/";
$temp_dir = "/bak/mysql/"; //temp directory
$site_temp_dir = "/bak/site/"; //temp directory
$rscfUsername = 'YOUR RACKSPACE USERNAME'; // the username for your rackspace account
$rscfApiKey = 'YOUR RACKSPACE API KEY'; // the api key for your account
$rscfContainer = 'YOUR RACKSPACE CONTAINER'; //rackspace containr
foreach($sites as $site) {
try{
exec("tar -czpf {$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz {$site_root}{$site}");
// check if the file is created
if(file_exists("{$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz")) {
$auth = new CF_Authentication($rscfUsername, $rscfApiKey);
$auth->ssl_use_cabundle();
$auth->authenticate();
$conn = new CF_Connection($auth);
$conn->ssl_use_cabundle();
// I allready created a container with this name otherwise user create_container
$container = $conn->get_container($rscfContainer);
// make a unique name with date in it so you know when it was created
$objectName = $site.$curr_date_time.'.tar.gz';
$store = $container->create_object($objectName);
$store->load_from_filename("{$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz"); // send to rackspace
}
} catch (Exception $e) {
print_r($e, true);
}
}
?>