Trouble with last_modified - Rackspace Cloud Files (PHP API) - php

Using Rackspace cloud files as a backup repository but new to their PHP API. I want to delete files past a certail age but having difficulty returning the last_modified date using the api.
$container = $conn->get_container('tmp');
$files = $container->list_objects();
foreach ($files as $file) {
echo $file; // echo filename
echo $file->last_modified(); // this syntax is incorrect
}

list_objects returns an array of strings, the names of the objects. You can also get PHP objects that allow you to use OOP to do things to those objects. So changing as little of your code as possible, we can convert the strings to objects:
$container = $conn->get_container('tmp');
$files = $container->list_objects();
foreach ($files as $file) {
echo $file; // echo filename
$file_obj = $container->get_object($file);
echo $file_obj->last_modified;
}
A little faster, just get an array of objects instead:
$container = $conn->get_container('tmp');
$files = $container->get_objects();
foreach ($files as $file) {
echo $file->name; // echo filename
echo $file->last_modified;
}
Node that code has not been tested, but should get you pretty close to something that works.

Related

Using PHP to Merge Multiple CSV Files

I'm new to this forum and also new to PHP, I'm building some very basic functions on a test site while I learn a little more about how to use PHP. One of the current project I'm experimenting with is combining two directories of CSV files.
I was hoping to use GLOB as sort of a *wildcard to gather up the files in each directory and then combine them. I know the way I'm using below isn't very memory efficient but this is just to learn with. The issue I'm having is setting the GLOB command to pickup all my CSV files and then getting that variable into a file_get_contents.
Here's my code..
$files = glob("http://www.website.com/1/*.csv");
foreach($files as $filepath) {
if ($handle = fopen($filepath, "r")) {
// ...
}
}
$files2 = glob("http://www.website.com/35/*.csv");
foreach($files2 as $filepath2) {
if ($handle2 = fopen($filepath2, "r")) {
// ...
}
}
file_put_contents('final_data.csv',
file_get_contents($files) .
file_get_contents($files2)
);
When you use Glob the resulting array doesn't contain the base path, so you have to add it, like this:
$basePath = '/path/to/csv';
foreach ($files = glob("$basePath/dir1/*.csv") as $filePath)
{
echo "$basePath/$filePath";
//
}
It would also make sense to read from local path instead of remote URL.

PHP Create Image Gallery From Directory And Subdirectories

I'm trying to make an image gallery that scans a main directory and creates a separate album for each subdirectory.
My structure is similar to this:
-Gallery
--Subdir 1
---Image 1
---Image 2
--Subdir 2
---Image 1
---Image 2
The idea is that each album is going to be made of a div with a class of web-gallery. Then there will be a header for the album title made from the subdirectories name. After that a list is generated of each image. This is going to be a one page gallery. If possible I would like to have a variable that sets how many albums are listed that way if I have 30 subdirectories my page doesn't get too crowded.
So far I've written this but it doesn't work. I'm not getting any errors or logs though it just doesn't work.
$dirs = glob('img/gallery_temp/*', GLOB_ONLYDIR);
foreach($dirs as $val) {
echo '<div class="web-gallery">';
echo "<h3><span>»</span> ".basename($val). "</h3>";
echo '<ul class="web-gallery-list">';
$files = glob($val.'*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
echo "<li><a href='".$file."'><img src='" . $file . "' alt='description'></a></li> \r\n";
}
echo "</ul>";
echo "</div>";
}
Simply add a / before *.{jpg,png,gif} like this:
$files = glob($val.'/*.{jpg,png,gif}', GLOB_BRACE);
This is because $val doesn't have a final / for the directory.
You might consider using "readdir" instead of glob. Glob is to find pathnames matching a pattern, see here: http://php.net/manual/en/function.glob.php and is known to be a bit problematic.
Readdir, if your directory is entirely images might be easier to use: http://php.net/manual/en/function.readdir.php
Couple this with is_dir() http://php.net/manual/en/function.is-dir.php to resolve your directories vs files. Here is a snippet
<?php
if ($handle = opendir('/galleries')) {
while (false !== ($entry = readdir($handle))) {
// this is a subdirectory
if (is_dir($entry)) {
}
// this is a file
else {
echo $entry;
}
}
closedir($handle);
}
?>
If you make it a recursive function you could actually have it traverse a number of subdirectories creating galleries within galleries.
I also found this fantastic little snippet that is very elegant on another stack question: Get Images In Directory and Subdirectory With Glob
$rdi = new RecursiveDirectoryIterator("uploads/prevImgs/");
$it = new RecursiveIteratorIterator($rdi);
foreach($it as $oneThing)
if (is_file($oneThing))
echo '<img src="'.$oneThing.'" /><br />';
Using SPL Library (PHP >= 5)
Better solution in your case
is to use SPL library (the most cross-platform)
$directory = new RecursiveDirectoryIterator("./img/gallery_temp", FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $fileinfo)
{
if($fileinfo->isDir())
{
// prevPath used to separate each directory listing and closing the bracket UL list
$prevPath = $it->getSubPath().DIRECTORY_SEPARATOR.$fileinfo->getFilename();
echo sprintf
(
"<div class='web-gallery'>
<h3><span>></span> %s</h3>
<ul>".PHP_EOL,
$fileinfo->getFilename()
);
}
if($fileinfo->isFile())
{
echo sprintf("<li><a href=''><img src='%s/%s' alt='description'></a></li>".PHP_EOL, $it->getSubPath(), $fileinfo->getFilename());
if($prevPath != $it->getSubPath())
echo("</ul>");
}
}
Note:
For more informations : SPL Documentation
DIRECTORY_SEPARATOR is a cross-platform constant, will use the
correct directory separator of the OS where are executed the code
FilesystemIterator::SKIP_DOTS, avoid to fetch the '.' and '..' dir
link level.
you can limit the depth of scanning with $it->setMaxDepth(5);

specify file types in RecursiveIteratorIterator

I am trying to create a form that allows a user to select checkboxes and when they submit it will search the web directory for the specific file types they checked off (jpg, gif, html, etc). I have the form done and it passes the variables for the types to an array, i have the rest of the form that zips the files and streams it for download. i am just stuck on how to specify the file types. this is what i have started with to make sure it can actually pull the file names and place them in a variable and it works:
$rootpath = '.';
$files = $_POST['file_types'];
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath)
);
foreach($fileinfos as $pathname => $fileinfo) {
if (!$fileinfo->isFile()) continue;{
$files[] .= substr($pathname, 2);
}
}
What should i use to pull the file types only specified in the following vaiable?
$_POST['file_types']
Edit:
For those who this may help this is the solution in the end that worked:
$rootpath = "../";
foreach ($types as $k => $v)
{
$types_array[] .= $v;
}
//Run all function then run it through checker and pull out the files we want
$directory = new RecursiveDirectoryIterator($rootpath,RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::LEAVES_ONLY);
$extensions = $types_array;
foreach ($iterator as $fileinfo) {
if (in_array($fileinfo->getExtension(), $extensions)) {
$files[] = substr($fileinfo->getPathname(), 2); /* Fill the array removing the "./" to make an echo of the file names easier to read for the end user */
}
}

Having troubling listing subdirectories recursively in PHP

I have the following code snippet. I'm trying to list all the files in a directory and make them available for users to download. This script works fine with directories that don't have sub-directories, but if I wanted to get the files in a sub-directory, it doesn't work. It only lists the directory name. I'm not sure why the is_dir is failing on me... I'm a bit baffled on that. I'm sure that there is a better way to list all the files recursively, so I'm open to any suggestions!
function getLinks ($folderName, $folderID) {
$fileArray = array();
foreach (new DirectoryIterator(<some base directory> . $folderName) as $file) {
//if its not "." or ".." continue
if (!$file->isDot()) {
if (is_dir($file)) {
$tempArray = getLinks($file . "/", $folderID);
array_merge($fileArray, $tempArray);
} else {
$fileName = $file->getFilename();
$url = getDownloadLink($folderID, $fileName);
$fileArray[] = $url;
}
}
}
Instead of using DirectoryIterator, you can use RecursiveDirectoryIterator, which provides functionality for iterating over a file structure recursively. Example from documentation:
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
This prints a list of all files and
directories under $path (including
$path ifself). If you want to omit
directories, remove the
RecursiveIteratorIterator::SELF_FIRST
part.
You should use RecursiveDirectoryIterator, but you might also want to consider using the Finder component from Symfony2. It allows for easy on the fly filtering (by size, date, ..), including dirs or files, excluding dirs or dot-files, etc. Look at the docblocks inside the Finder.php file for instructions.

PHP: Get list of all filenames contained within my images directory [duplicate]

This question already has answers here:
How to read a list of files from a folder using PHP? [closed]
(9 answers)
Closed 7 years ago.
I have been trying to figure out a way to list all files contained within a directory. I'm not quite good enough with php to solve it on my own so hopefully someone here can help me out.
I need a simple php script that will load all filenames contained within my images directory into an array. Any help would be greatly appreciated, thanks!
Try glob
Something like:
foreach(glob('./images/*.*') as $filename){
echo $filename;
}
scandir() - List files and directories inside the specified path
$images = scandir("images", 1);
print_r($images);
Produces:
Array
(
[0] => apples.jpg
[1] => oranges.png
[2] => grapes.gif
[3] => ..
[4] => .
)
Either scandir() as suggested elsewhere or
glob() — Find pathnames matching a pattern
Example
$images = glob("./images/*.gif");
print_r($images);
/* outputs
Array (
[0] => 'an-image.gif'
[1] => 'another-image.gif'
)
*/
Or, to walk over the files in directory directly instead of getting an array, use
DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories
Example
foreach (new DirectoryIterator('.') as $item) {
echo $item, PHP_EOL;
}
To go into subdirectories as well, use RecursiveDirectoryIterator:
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('.'),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($items as $item) {
echo $item, PHP_EOL;
}
To list just the filenames (w\out directories), remove RecursiveIteratorIterator::SELF_FIRST
You can also use the Standard PHP Library's DirectoryIterator class, specifically the getFilename method:
$dir = new DirectoryIterator("/path/to/images");
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
This will gives you all the files in links.
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/";
$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
{
//this will not display specified files
}
else
{
echo "<label >".$count.". </label>";
echo "".$filename."
";
$count++;
}
}
?>
Maybe this function can be useful in the future. You can manipulate the function if you need to echo things or want to do other stuff.
$wavs = array();
$wavs = getAllFiles('folder_name',$wavs,'wav');
$allTypesOfFiles = array();
$wavs = getAllFiles('folder_name',$allTypesOfFiles);
//explanation of arguments from the getAllFiles() function
//$dir -> folder/directory you want to get all the files from.
//$allFiles -> to store all the files in and return in the and.
//$extension -> use this argument if you want to find specific files only, else keept empty to find all type of files.
function getAllFiles($dir,$allFiles,$extension = null){
$files = scandir($dir);
foreach($files as $file){
if(is_dir($dir.'/'.$file)) {
$allFiles = getAllFiles($dir.'/'.$file,$allFiles,$extension);
}else{
if(empty($extension) || $extension == pathinfo($dir.'/'.$file)['extension']){
array_push($allFiles,$dir.'/'.$file);
}
}
}
return $allFiles;
}

Categories