Check if blob exists in Azure - php

I'm wondering if there is a way to check if a blob exists in a container?
$blob = $blobRestProxy->getBlob("mycontainer", "myblobname");
if($blob){
return 'exists';
} else {
return 'not exists';
}
I've tried this but im getting this message whenever the blob does not exists:
BlobNotFoundThe specified blob does not exist.
If exists, the code returns 'exists' naturally. I'm not interested in listing all blobs in the container and iterating until I find a match cause I have a lot of blobs.

When the blob does not exist, the function getBlob will raise a ServiceException exception and exit the PHP progress, the following code will not work.
Please try to add the try catch statement in your code, E.G.
try {
$blob = $tableRestProxy->getBlob("mycontainer", "myblobname");
return 'exists';
} catch (ServiceException $e) {
return 'not exists';
}

so:
$exists = $storageClient->blobExists(<container name>, <blob name>);
Should give you what you're after.

Though older post, below is azure java client sample code, in case if it helps.
//getting the info from external configuration
String accountName = getStorageAccountName();
String accessKey = getAccessKey();
String container = getContainerName();
//create connection string
String connString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",accountName,accessKey);
// create account
CloudStorageAccount account= CloudStorageAccount.parse(connString );
// create client
CloudBlobClient blobClient = account.createCloudBlobClient();
// create container
CloudBlobContainer container = blobClient.getContainerReference(container);
// fetch item from list
Iterable<ListBlobItem> blobItems = container.listBlobs();
blobItems .forEach(item -> {
if (item instanceof CloudBlockBlob){
//additional condition can be added to check leased
// need to check if the blob item exists first
if((CloudBlockBlob) blobItem).exists()){
//custom business logic
}
// to check container exists and perform logic use below
// ((CloudBlobContainer) item.getContainer()).exists
}
});

Related

PHP autoload.php not found

so this is my code:
<?php
echo 'hey1';
set_time_limit(0);
date_default_timezone_set('UTC');
echo 'hey2';
require __DIR__.'/../vendor/autoload.php';
echo 'hey3';
/////// CONFIG ///////
$username = 'NetsGets';
$password = 'NetsGetsWebsite';
$debug = true;
$truncatedDebug = false;
//////////////////////
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$feed = $ig->discover->getExploreFeed();
// Let's begin by looking at a beautiful debug output of what's available in
// the response! This is very helpful for figuring out what a response has!
$feed->printJson();
// Now let's look at what properties are supported on the $feed object. This
// works on ANY object from our library and will show what functions and
// properties are supported, as well as how to call the functions! :-)
$feed->printPropertyDescriptions();
// The getExploreFeed() has an "items" property, which we need. As we saw
// above, we should get it via "getItems()". The property list above told us
// that it will return an array of "Item" objects. Therefore it's an ARRAY!
$items = $feed->getItems();
// Let's get the media item from the first item of the explore-items array...!
$firstItem = $items[0]->getMedia();
// We can look at that item too, if we want to... Let's do it! Note that
// when we list supported properties, it shows everything supported by an
// "Item" object. But that DOESN'T mean that every property IS available!
// That's why you should always check the JSON to be sure that data exists!
$firstItem->printJson(); // Shows its actual JSON contents (available data).
$firstItem->printPropertyDescriptions(); // List of supported properties.
// Let's look specifically at its User object!
$firstItem->getUser()->printJson();
// Okay, so the username of the person who posted the media is easy... And
// as you can see, you can even chain multiple function calls in a row here
// to get to the data. However, be aware that sometimes Instagram responses
// have NULL values, so chaining is sometimes risky. But not in this case,
// since we know that "user" and its "username" are always available! :-)
$firstItem_username = $firstItem->getUser()->getUsername();
// Now let's get the "id" of the item too!
$firstItem_mediaId = $firstItem->getId();
// Finally, let's get the highest-quality image URL for the media item!
$firstItem_imageUrl = $firstItem->getImageVersions2()->getCandidates()[0]->getUrl();
// Output some statistics. Well done! :-)
echo 'There are '.count($items)." items.\n";
echo "The first item has media id: {$firstItem_mediaId}.\n";
echo "The first item was uploaded by: {$firstItem_username}.\n";
echo "The highest quality image URL is: {$firstItem_imageUrl}.\n";
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
?>
After running this code, the only things that print are hey1 and hey2. Based on my own reasearch, I concluded that autoload.php is one of the necessery files for the composer to run, but it also seems to be the problem that stops the php from running. This code is from https://github.com/mgp25/Instagram-API. Pease help!
1) If you don't have Composer, install it. For example:
sudo apt-get install composer -y
2) Run:
composer require mgp25/instagram-php
3) Type:
cd vendor
ls
The very first file you see listed should be autoload.php.

How to check on Rackspace if the file is uploaded or not?

I'm working with the Rackspace PHP API, where I've got a requirement to check the file, if it exists then do something and if not then do something.
try {
$file = $container->getObject($end_element);
$fileExists = TRUE;
}
catch(Exception $e) {
$fileExists = FALSE;
}
if ($fileExists) {
// File is their, it needs to be rewrite/overwrite
$file->setContent(fopen('sites/default/files/rackspace/' . $end_element, 'r+'));
$file->update();
// I'm getting this http://docs.rackspace.com/sdks/api/php/class-OpenCloud.ObjectStore.Resource.DataObject.html which I printted print_r($file->update());
}
else {
// New file just to upload
$container->uploadObject($end_element, fopen('sites/default/files/rackspace/' . $end_element, 'r+'), array());
}
To see whether an object exists in a remote container, try using the objectExists method like so:
if ($container->objectExists('objectName.txt')) {
// The object exists
} else {
// The object doesn't exist
}
This will perform a HEAD request on that object, wrapping any 404 failure response in a try/catch block for you.
In terms of finding out the date the object was created, the API only tells you the date of last modification. This will be the create date if you haven't modified the object since it was first uploaded.
To find out the last modified datetime, you need to run:
$object = $container->getObject('objectName.txt');
$created = $object->getLastModified();

Laravel : How do I compare/obtain specific datas from cache?

In my normal polling Laravel chat app, I will save new messages sent by a user into a file cache with the key as a string, getting its value from date(current_time) function and the body of the message.
Then, when I want to obtain those messages, I will use the last Poll value $lastPolled = Session::get('lastPolled') and compare with the key in the cache. Keys that are greater than the $lastPolled value will have their data to be taken as new messages and appended into the conversations.
Finally, I will update the last polled session value Session::put('lastPolled',date(Y-m-d H:i:s)
So, how do I compare $lastPolled with all the keys in cache and get each key's values? Something along the lines of:
$latestMessages = array();
foreach(KeysInCache as Key=>value){
if($lastPolled>Key)
array_push($latestMessages,Key=>value);
}
Thank you!
P.s. bonus points for better suggestions. Oh and I can't use memcache/redis/otherSuperCaches for technical reasons, only file/database cache. :(
Why not try some thing like this by creating cache files based on timestamp or key :
Further details and suggestions on same at : http://evertpot.com/107/
// This is the function you store information with function
store($key,$data,$ttl) {
// Opening the file
$h = fopen($this->getFileName($key),'w');
if (!$h) throw new Exception('Could not write to cache');
// Serializing along with the TTL
$data = serialize(array(time()+$ttl,$data));
if (fwrite($h,$data)===false) {
throw new Exception('Could not write to cache');
}
fclose($h);
}
// General function to find the filename for a certain key private
function getFileName($key) {
return '/tmp/s_cache' . md5($key);
}
// The function to fetch data returns false on failure function
fetch($key) {
$filename = $this->getFileName($key);
if (!file_exists($filename) || !is_readable($filename)) return false;
$data = file_get_contents($filename);
$data = #unserialize($data);
if (!$data) {
// Unlinking the file when unserializing failed
unlink($filename);
return false;
}
// checking if the data was expired
if (time() > $data[0]) {
// Unlinking
unlink($filename);
return false;
}
return $data[1];
}
}

Amazon $s3->create_object() returns 200 but object isn't created

I'm trying to upload an image to S3 using PHP, and it seems like it should be working but the image doesn't appear. The code to upload is this:
$s3 = new AmazonS3(array("key"=><mykey>,"secret"=><mysecret>));
$s3->ssl_verification = false;
if ($s3->if_bucket_exists($i_sBucket)) {
$obj = $s3->create_object($i_sBucket,$i_sFileName,array('body'=>$i_sData));
if ($obj->isOK()) {
return true;
} else {
//log error
}
} else {
// log error
}
When I run this, I get these important values:
$obj->isOK() = true
$obj["status"] = 200
$obj["body"] = false
$obj["_info"]["url"] = the appropriate destination URL
$obj["_info"]["http_code"] = 200
But if I check the bucket through the web interface, or try to access the file, it's not there.
Any ideas?
Thanks in advance...
What values do you have for $i_sBucket and $i_sFileName?
My guess is that those variables don't match any existing folder.

check if object exists in Cloud Files (PHP API)

I've just started working with the PHP API for Rackspace Cloud Files. So far so good-- but I am using it as sort of a poor man's memcache, storing key/value pairs of serialized data.
My app attempts to grab the existing cached object by its key ('name' in the API language) using something like this:
$obj = $this->container->get_object($key);
The problem is, if the object doesn't exist, the API throws a fatal error rather than simply returning false. The "right" way to do this by the API would probably be to do a
$objs = $this->container->list_objects();
and then check for my $key value in that list. However, this seems way more time/CPU intensive than just returning false from the get_object request.
Is there a way to do a "search for object" or "check if object exists" in Cloud Files?
Thanks
I sent them a pull request and hope it'll get included.
https://github.com/rackspace/php-cloudfiles/pull/35
My pull-request includes an example, for you it would be similar to this:
$object = new CF_Object($this->container, 'key');
if ($object->exists() === false) {
echo "The object '{$object->name}' does not exist.";
}
I have more general way to check if object exists:
try {
$this->_container->get_object($path);
$booExists = true;
} catch (Exception $e) {
$booExists = false;
}
If you dump the $object, you'll see that content_length is zero. Or, last modified will be a zero length string.
Example:
$object = new CF_Object($container, 'thisdocaintthere.pdf');
print_r($object->content_length);
There is also, deep in the dumped parent object, a 404 that will return, but it's private, so you'd need to some hackin' to get at it.
To see this, do the following:
$object = new CF_Object($container, 'thisdocaintthere.pdf');
print_r($object->container->cfs_http);
You'll see inside that object a response_status that is 404
[response_status:CF_Http:private] => 404
I know I'm a little late to the party, but hopefully this will help someone in the future: you can use the objectExists() method to test if an object is available.
public static function getObject($container, $filename, $expirationTime = false)
{
if ($container->objectExists($filename)) {
$object = $container->getPartialObject($filename);
// return a private, temporary url
if ($expirationTime) {
return $object->getTemporaryUrl($expirationTime, 'GET');
}
// return a public url
return $object->getPublicUrl();
}
// object does not exist
return '';
}
Use like...
// public CDN file
$photo = self::getObject($container, 'myPublicfile.jpg');
// private file; temporary link expires after 60 seconds
$photo = self::getObject($container, 'myPrivatefile.jpg', 60);
If you do not want to import opencloud to perform this check you can use the following:
$url = 'YOUR CDN URL';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
if($code!='200') {
echo 'failed';
} else {
echo 'exists';
}

Categories